这个问题在这里已经有了答案:
Methods in ES6 objects: using arrow functions
(6 个回答)
4年前关闭。
我正在尝试 ES6 并希望在我的函数中包含一个属性,就像这样
var person = {
name: "jason",
shout: () => console.log("my name is ", this.name)
}
person.shout() // Should print out my name is jason
但是,当我运行此代码控制台时,只记录
my name is
.我究竟做错了什么?
最佳答案
简短回答:this
点在最近的边界this
- 在提供的代码中 this
在封闭范围内找到。
更长的答案:箭头函数
do not have this
, arguments
or other special names bound at all - 创建对象时的名称this
在封闭范围内找到,而不是 person
目的。通过移动声明,您可以更清楚地看到这一点:
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);
}
};
关于javascript - 箭头函数和这个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28798330/