10

我正在尝试理解 ECMAScript 6 中的箭头函数。

这是我在阅读时遇到的定义:

箭头函数具有隐式this绑定,这意味着this箭头函数内部的值与this定义箭头函数的范围内的值完全一样!

根据定义,我认为thisanarrow function应该包含与定义箭头函数相同的块级值。

代码:

var test = {
  id: "123123",
  k: {
    laptop: "ramen",
    testfunc: () => console.log(this)
  }
}

console.log(test.k.testfunc);

但是,我从代码中得到了这个结果

function testfunc() {
    return console.log(undefined);
}

我认为我会得到的输出是:

{"laptop": "ramen"}

如果我运行这个

console.log(test.k.testfunc());

4

2 回答 2

5

让我们转换成等效的 ES5 代码:

var test = {
  id: "123123",
  k: {
    laptop: "ramen",
    testfunc: function(){return console.log(this)}.bind(this)
  }
}

请记住,这this取决于您如何调用该函数。外部this不在函数内部,因此它将默认为undefined严格模​​式。

下面的简化场景:

console.log(this) // undefined

var test = {
  a: this // same `this` as above
}
于 2015-07-27T07:54:22.473 回答
3

您正在定义的相同范围内定义箭头函数var test。如果您test在全局范围内定义,那么箭头函数的上下文也将是全局范围。

如果您在方法内部定义测试,箭头函数将共享方法的上下文。

function method() {
  const self = this;

  const test = {
    foo: () => console.log(self === this);
  }

  test.foo()
  // console: true
}
于 2015-07-27T07:59:50.973 回答