为什么'this'在箭头函数中引用时返回'undefined',但在匿名函数上调用时不返回?

Oma*_*uez 1 javascript node.js javascript-objects arrow-functions

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

例如

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

T.J*_*der 5

由于箭头的功能没有自己的this,他们关闭了this调用上下文的.但是非箭头函数,如果它们没有约束,则this根据它们的调用方式而定.我假设您正在调用这些函数:

obj.getScopeWithArrow();
obj.getScopeWithAnonymous();
Run Code Online (Sandbox Code Playgroud)

在第一种情况下,箭头函数再次没有得到它自己,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();
Run Code Online (Sandbox Code Playgroud)