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

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

例如

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

由于箭头函数没有自己的this ,所以它们closures了调用上下文的this 。 但是非箭头函数,如果没有绑定,就根据它们的调用方式来进行 。 我假设你正在调用这样的函数:

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

在第一种情况下,箭头函数并没有得到它自己的东西,所以你怎么称呼它并不重要。 在第二种情况下,它确实很重要,并且像这样调用它使得在调用中引用obj引用的同一对象。


另外:在你的例子中,你必须在严格模式,因为this只能在严格模式下undefined

另外2:关于你的方法名称: this和“范围”相互之间很less有关系。


一些例子:

 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(); 

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

没有这个绑定

在箭头函数之前,每个新函数都定义了它自己的这个值(一个构造函数中的新对象,严格模式函数调用中未定义的对象,如果该函数被称为“对象方法”的上下文对象等)。 这被certificate是一个面向对象的编程风格的烦人。

如果目标是避免编写函数,则可以避免使用冒号,并用新的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());