【问题标题】:How Arrow function work inside constructor?箭头函数如何在构造函数中工作?
【发布时间】: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


【解决方案1】:

在构造函数中this 指的是正在构造的对象。为什么你还能做this.b ='b';

由于箭头函数只是捕获当前上下文,它在构造函数中捕获对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    • 2018-11-29
    相关资源
    最近更新 更多