【问题标题】:Arrow Function in Object Literal [duplicate]对象文字中的箭头函数
【发布时间】:2016-08-11 13:43:45
【问题描述】:

我试图弄清楚为什么用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(); 不是用arrowObject 作为this 调用的?

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

【问题讨论】:

  • 当外部上下文(对象被创建的地方)有this作为窗口对象...箭头函数将使用创建者this值作为它的this上下文

标签: javascript ecmascript-6 babeljs object-literal arrow-functions


【解决方案1】:

请注意,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);

我试图弄清楚为什么用window 作为this 调用对象文字中的箭头函数。

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

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

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

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

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

【讨论】:

  • 我确实在使用 Fiddle(没有“use strict;”)。很好的答案,我明白现在发生了什么。
猜你喜欢
  • 2018-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-05
相关资源
最近更新 更多