NodeJS中的ES6:对象文字中的箭头函数,返回的“this”值是什么?

我只是玩弄箭头函数,并尝试使用它们作为对象字面上的属性,如下所示:

var obj = { a: () => { return this; }, b: function () { return this; }, }; 

但是,当我testing这个,我不能解释从obj.a()返回的是什么。

 console.log(obj.a()); //=> {} console.log(obj.b()); //=> { a: [Function], b: [Function] } 

它是obj的原型吗?

这很可能会引用nodejs 默认对象 (相当于window)。 它可能被定义为别的东西取决于你的对象被放置在什么范围。

如果你在你的项目中use strict ,这将是未定义的。

胖箭头function让你回到父母的范围。 意味着在这种情况下是没有用的,因为它会让你回到错误的范围。

当你有一个callback,你想要在相同的范围内,脂肪箭头是有用的。 (记得var self = this ?)

 var obj = { txt: 'TEXT', a: function (cb) { return cb(); }, b: function () { var self = this; this.a(function() { // Normal funciton, you need the self //console.log(val); console.log(this.txt) console.log(self.txt); }) }, c: function () { this.a(() => { console.log(this.txt) }) }, }; console.log('--- B') obj.b(); console.log('--- C') obj.c(); 

a中的返回对象是全局对象,如果设置use strict ,它将是未定义的。

 var obj = { a: () => { //this = global scope return this; }, b: function () { return this; }, };