我正在使用 node.js v6.7.0 并在声明一个引用“this”的对象时,如果它在箭头函数内则返回未定义,但当它在常规匿名函数内时它返回对象本身(是我想要的)
例如
let obj = {
key: 'val',
getScopeWithArrow: () => {return this;}, //returns undefined
getScopeWithAnonymous: function() {return this;} //returns the object properly
}
因为箭头函数没有自己的 this
,所以它们关闭调用上下文的 this
。但非箭头函数,如果它们未绑定(bind),则根据它们的调用方式 采用this
。我假设您是这样调用这些函数的:
obj.getScopeWithArrow();
obj.getScopeWithAnonymous();
同样,在第一种情况下,箭头函数没有得到它自己的 this
,因此您如何调用它并不重要。在第二种情况下,它确实很重要,并且像这样调用它会使调用中的 this
引用 obj
引用的同一对象。
另外:在你的例子中,你必须处于严格模式,因为this
在严格模式下只能是undefined
。
另外 2:关于您的方法名称:this
和“scope”之间的关系非常非常小。
一些例子:
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();