对象文字中的箭头函数

IT技术 javascript ecmascript-6 babeljs object-literal arrow-functions
2021-01-15 20:46:27

我试图弄清楚为什么用windowas调用对象文字中的箭头函数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);
  }
};

为什么不用asarrowObject.printName();调用arrowObjectthis

控制台日志来自Fiddleuse strict;未使用的地方)。

1个回答

请注意,Babel 翻译假设采用严格模式,但您的结果window表明您正在以松散模式运行代码。如果你告诉 Babel 假设为松散模式,它的转译是不同的

var _this = this;                    // **

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

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

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

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

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

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

如果我们将您的初始化程序分解为其逻辑等效项,那么创建箭头函数的上下文可能会更清楚一些:

var arrowObject = {};
arrowObject.name = 'arrowObject';
arrowObject.printName = () => {
  console.log(this);
};
我确实在使用 Fiddle(没有“使用严格;”)。很好的答案,我明白现在发生了什么。
2021-03-15 20:46:27