对象字面量中的箭头函数

Arrow Function in Object Literal

我想弄清楚为什么对象字面量中的箭头函数是用 window 作为 this 调用的。有人可以给我一些见解吗?

var arrowObject = {
  name: 'arrowObject',
  printName: () => {
    console.log(this);
  }
};

// Prints: Window {external: Object, chrome: Object ...}
arrowObject.printName();

以及按预期工作的对象:

var functionObject = {
  name: 'functionObject',
  printName: function() {
    console.log(this);
  }
};

// Prints: Object {name: "functionObject"}
functionObject.printName();

根据 Babel REPL,它们被转译为

var arrowObject = {
  name: 'arrowObject',
  printName: function printName() {
    console.log(undefined);
  }
};

var functionObject = {
  name: 'functionObject',
  printName: function printName() {
    console.log(this);
  }
};

为什么 arrowObject.printName(); 没有像 this 那样用 arrowObject 调用?

控制台日志来自 Fiddle(未使用 use strict;)。

请注意,Babel 翻译采用严格模式,但 window 的结果表明您 运行 您的代码处于松散模式。如果你告诉 Babel 采用松散模式,它的转译 is different:

var _this = this;                    // **

var arrowObject = {
  name: 'arrowObject',
  printName: function printName() {
    console.log(_this);              // **
  }
};

请注意 _this 全局和 console.log(_this);,而不是来自严格模式转译的 console.log(undefined);

I'm trying to figure out why an arrow function in an object literal is called with window as this.

因为箭头函数从创建它们的上下文中继承 this。显然,你在哪里做的:

var arrowObject = {
  name: 'arrowObject',
  printName: () => {
    console.log(this);
  }
};

...thiswindow。 (这表明您没有使用严格模式;我建议在没有明确理由不这样做的情况下使用它。)如果它是其他东西,例如严格模式全局代码的 undefinedthis 在箭头函数中将是另一个值。

如果我们将你的初始化器分解成它的逻辑等价物,创建箭头函数的上下文可能会更清楚一些:

var arrowObject = {};
arrowObject.name = 'arrowObject';
arrowObject.printName = () => {
  console.log(this);
};