【发布时间】:2017-06-18 08:40:54
【问题描述】:
我对构造函数中的箭头函数有点困惑。
据我所知:如果我们使用箭头函数,关键字 this 不会反弹到实际函数。它是从父作用域继承而来的。
举个例子:
var d = {
b: 'b',
x: () =>{
console.log(this); // this will return Window Object.
}
}
d.x();
它将打印Window 对象。没关系。
但是在构造函数中
function A(){
this.b ='b';
this.x = () =>{
console.log(this);
}
}
var c = new A()
c.x();
此打印对象c。但据我说它应该返回窗口对象。为什么?
【问题讨论】:
-
你的词法作用域已经是
A(否则this.x = ...一开始就不会起作用)。 -
这样做会很有趣:b=new A();c=new A(); b.x=c.x;
标签: javascript ecmascript-6 arrow-functions