这个内部对象方法的值?

Value of this inside object method?

在使用箭头函数调用函数时,我对 this 的值感到非常困惑。举个例子:

var obj = {
  property: 5,
  func1: function () {
    console.log(this.property);
  },
  func2: () => {
    console.log(this.property);
  }
}

当我将这段代码放在浏览器控制台上时,一件有趣的事情发生了,func1() 将按预期输出 5 *,但是当我 运行 func2 我得到了 undefined。这里发生了什么?为什么 func2this 的值引用全局对象(在本例中为 Window)。

我想我期待那个输出,因为它就是这样工作的,这就是 Alan 和 slevetman 解释 here and here respectively. But according to the Jason's explanation

的原因

Arrow functions do not have their own this value. The value of this inside an arrow function is always inherited from the enclosing scope.

那么,为什么 func2 里面的 this 的值没有继承他的封闭作用域 obj 的值?

So, why the value of this inside func2 is not inheriting the value of his enclosing scope obj?

这里的obj不是"enclosing"范围。您在其中定义 obj 的范围是 "enclosing" 范围。

考虑这个例子:

var obj = {
  property: 5,
  func1: function () {
      let func2 = () => {
        console.log(this.property); 
      }
      func2();
  },
}
obj.func1(); // logs 5
obj.func1.call({
   property: 6
}) // logs 6

当调用内部 func2 时,this 关键字引用 obj 作为包装器 func1 函数中的 this 引用 objfunc2 继承 this 值。内部箭头函数不绑定它自己的 this 值。

func2中的this是继承函数本身作用域的值,仅此而已。为了让它工作,你必须做这样的事情:

var obj = {
    property: 5,
    func1: function () {
        console.log(this.property); // shows 5
    },
    func2: () => {
        console.log(this.property); // shows undefined
        this.property = 6;
        console.log(this.property); // shows 6
    }
}