jas*_*328 19 javascript this ecmascript-6 arrow-functions
我正在尝试ES6,并希望在我的函数中包含一个属性,就像这样
var person = {
name: "jason",
shout: () => console.log("my name is ", this.name)
}
person.shout() // Should print out my name is jason
Run Code Online (Sandbox Code Playgroud)
但是,当我运行此代码控制台时只记录日志my name is.我究竟做错了什么?
Sea*_*ira 33
简答:this最近边界处的点this- 在提供的代码中this可以找到封闭范围.
更长的答案:箭头功能 没有this在创建它们时绑定它们this,arguments或结合其它特殊名字都 -正在创建对象时的名称this是在封闭范围内,未找到person对象.通过移动声明,您可以更清楚地看到这一点:
var person = {
name: "Jason"
};
person.shout = () => console.log("Hi, my name is", this);
Run Code Online (Sandbox Code Playgroud)
当翻译成ES5中箭头语法的模糊近似时更加清晰:
var person = {
name: "Jason"
};
var shout = function() {
console.log("Hi, my name is", this.name);
}.bind(this);
person.shout = shout;
Run Code Online (Sandbox Code Playgroud)
在这两种情况下,this(对于shout函数)指向与person定义的范围相同的范围,而不是函数在添加到person对象时附加到的新范围.
你不能让箭头函数以这种方式工作,但是,正如@kamituel在他的回答中指出的那样,你可以利用ES6中较短的方法声明模式来获得类似的空间节省:
var person = {
name: "Jason",
// ES6 "method" declaration - leave off the ":" and the "function"
shout() {
console.log("Hi, my name is", this.name);
}
};
Run Code Online (Sandbox Code Playgroud)
kam*_*uel 25
同意@Sean Vieira - 在这种情况下this绑定到全局对象(或者,如注释中指出的,更一般地说是封闭范围).
如果您想要更短的语法,还有另一种选择 - 增强的对象文字支持属性函数的短语法.this将受到你期望的约束.见shout3():
window.name = "global";
var person = {
name: "jason",
shout: function () {
console.log("my name is ", this.name);
},
shout2: () => {
console.log("my name is ", this.name);
},
// Shorter syntax
shout3() {
console.log("my name is ", this.name);
}
};
person.shout(); // "jason"
person.shout2(); // "global"
person.shout3(); // "jason"
Run Code Online (Sandbox Code Playgroud)
Ten*_*ink 10
公认的答案是出色,简洁和清晰的,但我将详细说明肖恩·维埃拉(Sean Vieira)所说的话:
箭头函数根本没有绑定此参数或其他特殊名称。
由于arrow函数没有“ this”,因此它使用父级的“ this”。“ this”始终指向父对象,而person对象的父对象是Window(如果您在浏览器中)。
为了证明它可以在您的控制台中运行:
var person = {
name: "Jason",
anotherKey: this
}
console.log(person.anotherKey)
Run Code Online (Sandbox Code Playgroud)
您将获得Window对象。
我认为这是思考问题的一种非常有用的方法。这还不是完整的故事,因为对象文字的“ this”是另一个讨论。
| 归档时间: |
|
| 查看次数: |
8492 次 |
| 最近记录: |