【发布时间】:2018-11-23 04:39:14
【问题描述】:
我理解箭头函数中的“this”指向上层执行上下文中的this。
var name = 'aaa';
const person = {
name: 'bbb',
getName: () => {return console.log(this.name)}
}
person.getName();
所以我知道 getName() 在上面的代码中记录了全局对象的名称。
const name = 'aaa';
const Person = function() {
this.name = 'bbb';
this.getName = () => {return console.log(this.name)}
}
const test = new Person();
test.getName();
但是,此代码中的测试对象是作为 Person 构造函数创建的对象。因此,我认为测试对象的 getName() 与上面代码中对象方法中使用的 this 相同。我理解错了什么?
【问题讨论】:
标签: javascript ecmascript-6 arrow-functions