Js 中荒谬的范围界定

问题描述

有人可以向我解释为什么第二个函数调用返回 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());

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...