Js 中可笑的作用域

Ridiculous scoping in Js

有人可以向我解释为什么第二个函数调用 returns 未定义吗?我认为没有理由这样做。对象方法的引用保存在一个变量中,所以应该打印出来。为什么结果未定义?第一个函数调用成功,唯一的区别是第二个函数调用存储在变量中。

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