问题描述
有人可以向我解释为什么第二个函数调用返回 undefined 吗?我看不出有什么原因。对象方法的引用存储在一个变量中,因此应该打印出来。为什么结果未定义?第一个函数调用成功,唯一的区别是第二个是存储在一个变量中。
const module = {
x: 42,getX: function() {
return this.x;
}
};
//1 - returns 42
console.log(module.getX());
//2 - returns undefined
const unboundGetX = module.getX;
console.log(unboundGetX());
解决方法
因为unboundGetX函数被全局window变量调用,unboundGetX()
就像写window.unboundGetX()
所以this > 将引用全局范围,即“window”对象,所以它也就像你写的 return window.x
一样,它在逻辑上是“未定义的”。
像这样将作用域绑定到同一个对象会更好:
const module = {
x: 42,getX: function() {
return this.x;
}
};
console.log(module.getX());
const unboundGetX = module.getX.bind(module); // we bind getX function to module scope instead of the global scope (which is the window variable)
console.log(unboundGetX());