简答:this 指向最近的边界 this - 在提供的代码中,this 位于封闭范围内。
更长的答案:箭头函数在创建时绑定它们的this do not have this, arguments or other special names bound at all - 在创建对象时,名称this 位于封闭范围内,而不是@987654331 @ 目的。通过移动声明可以更清楚地看到这一点:
var person = {
name: "Jason"
};
person.shout = () => console.log("Hi, my name is", this);
当翻译成 ES5 中箭头语法的模糊近似时会更加清晰:
var person = {
name: "Jason"
};
var shout = function() {
console.log("Hi, my name is", this.name);
}.bind(this);
person.shout = shout;
在这两种情况下,this(对于喊函数)指向与定义 person 相同的范围,而不是函数添加到 person 对象时附加到的新范围。
您不能使箭头函数以这种方式工作,但是,正如@kamituel 在his answer 中指出的那样,您可以利用 ES6 中较短的方法声明模式获得类似的空间节省:
var person = {
name: "Jason",
// ES6 "method" declaration - leave off the ":" and the "function"
shout() {
console.log("Hi, my name is", this.name);
}
};