【问题标题】:Why does 'this' return 'undefined' when referred in an arrow function but doesn't when called on an anonymous function? [duplicate]为什么“this”在箭头函数中引用时返回“未定义”,但在匿名函数中调用时却没有? [复制]
【发布时间】:2017-02-20 13:53:27
【问题描述】:

我正在使用 node.js v6.7.0 并在声明一个引用 'this' 的对象时,如果它在箭头函数内部,它会返回 undefined 但是当它在常规匿名函数内部时,它会返回对象本身(是我想要的)

例如

let obj = {
  key: 'val',
  getScopeWithArrow: () => {return this;}, //returns undefined
  getScopeWithAnonymous: function() {return this;} //returns the object properly
}

【问题讨论】:

标签: javascript node.js javascript-objects arrow-functions


【解决方案1】:

因为箭头函数没有自己的this,它们关闭调用上下文的this。但是非箭头函数,如果它们没有被绑定,则根据 它们的调用方式采用this。我假设你是这样调用这些函数的:

obj.getScopeWithArrow();
obj.getScopeWithAnonymous();

同样,在第一种情况下,箭头函数没有自己的this,因此无论您如何调用它都无关紧要。在第二种情况下,它确实很重要,并且像这样调用它会使调用中的this 引用同一个对象obj 引用。


另外:在您的示例中,您必须处于严格模式,因为this 在严格模式下只能是undefined

另外 2:关于您的方法名称:this 和“范围”彼此之间几乎没有关系。


一些例子:

function showThis(label, t) {
  if (t === window) {
    console.log(label, "(global object)");
  } else {
    console.log(label, t);
  }
}
// Loose mode by default in a non-module script element
let obj = {
  arrow: () => {
    showThis("arrow says ", this);
  },
  normal: function() {
    showThis("normal says ", this);
  }
};
obj.arrow();  // global object (window on browsers)
obj.normal(); // obj

function foo() {
  // Here, we're in strict mode
  "use strict";
  let obj = {
    arrow: () => {
      showThis("arrow says ", this);
    },
    normal: function() {
      showThis("normal says ", this);
    }
  };
  obj.arrow();  // undefined
  obj.normal(); // obj

}
foo();

【讨论】:

  • 这么好的答案,谢谢 T.J.感谢您花时间解释它!
【解决方案2】:

根据 developer.mozilla.org (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)

无此绑定

直到箭头函数,每个新函数都定义了自己的 this 值(在构造函数的情况下是一个新对象,在严格模式函数调用中未定义,如果函数被称为“对象方法”,则为上下文对象等) .事实证明,这种面向对象的编程风格很烦人。

但是

如果目标是避免编写函数,您可以避免使用冒号并使用新的 ECMA6 对象函数声明语法来声明您的方法。

let obj = {
  key: 'val',
  getScopeWithParens() {return this;}, //returns object
  getScopeWithAnonymous: function() {return this;} //returns the object properly
}

console.log(obj.getScopeWithAnonymous());
console.log(obj.getScopeWithParens());

【讨论】:

  • 哦,我不知道 ES6 上的新语法,顺便谢谢你,也许我应该试试
猜你喜欢
  • 2016-11-30
  • 2017-10-31
  • 1970-01-01
  • 1970-01-01
  • 2017-03-02
  • 1970-01-01
  • 2016-09-08
相关资源
最近更新 更多