javascript – 箭头函数的这个值
作者:互联网
参见英文答案 > Methods in ES6 objects: using arrow functions 4个
> How does the “this” keyword in Javascript act within an object literal? 4个
我想了解ECMAScript 6中的箭头功能.
这是我在阅读时遇到的定义:
Arrow functions have implicit
this
binding, which means that the
value of thethis
value inside of an arrow function is aways the
same as the value ofthis
in the scope in which the arrow function
is defined!
根据定义,我相信箭头函数应该包含与定义箭头函数相同的块级别值.
码:
var test = {
id: "123123",
k: {
laptop: "ramen",
testfunc: () => console.log(this)
}
}
console.log(test.k.testfunc);
但是,我从代码中得到了这个结果
function testfunc() {
return console.log(undefined);
}
我以为我会得到的输出是:
{"laptop": "ramen"}
如果我跑了
的console.log(test.k.testfunc());
解决方法:
让我们转换为等效的ES5代码:
var test = {
id: "123123",
k: {
laptop: "ramen",
testfunc: function(){return console.log(this)}.bind(this)
}
}
请记住,这取决于您如何调用该函数.外部不在函数内部,因此在严格模式下默认为undefined.
简化方案如下:
console.log(this) // undefined
var test = {
a: this // same `this` as above
}
标签:arrow-functions,javascript,ecmascript-6 来源: https://codeday.me/bug/20190927/1823931.html