MDN给出以下两个箭头函数的例子
示例 1
var adder = {
base: 1,
addThruCall: function(a) {
var f = v => v + this.base;
var b = {
base: 2
};
return f.call(b, a);
}
};
console.log(adder.addThruCall(1)); // 2
示例 2
'use strict';
var obj = {
i: 10,
b: () => console.log(this.i, this),
c: function() {
console.log(this.i, this);
}
}
obj.b(); // prints undefined, Window {...} (or the global object)
obj.c(); // prints 10, Object {...}
问题
-
例1中的
this.base
指向adder.base
示例 2 中属性 this.i
解析为undefined
b
的 如果箭头函数没有 this
值,this.base
不应该也解析为 undefined
吗?
最佳答案
箭头函数有一个“this”,它是您定义它们时当前范围内的任何“this”。
在你的第二个例子中,在箭头函数 b()
中,因为你没有定义“this”的特定父范围,“this”指向“Window”(在浏览器上下文中)
同样在你的第二个例子中,在命名函数 c()
中,function()...
引入了一个范围,这是 undefined
默认情况下。
所以你看到的完全是意料之中的。但是,如您所见,“this”掌握起来比较复杂,因此良好的代码风格建议尽可能避免使用它。在这种情况下,您可能需要使用闭包。
有趣的是在另一个问题中读到这个:How does the "this" keyword work?
关于javascript - 箭头函数作为方法 : Value of this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48373388/