我对 JavaScript `this` 的理解正确吗?

Is my understanding of JavaScript `this` correct?

鉴于以下摘自本网站 a well known question 的代码段:

x = 9;
var module = {
    x: 81,
    getX: function () {
        return this.x;
    }
};

module.getX(); // 81

var getX = module.getX;
getX(); // 9, because in this case, "this" refers to the global object

// create a new function with 'this' bound to module
var boundGetX = getX.bind(module);
boundGetX(); // 81

我的理解逻辑是:

但是,由于大多数人(过去)不知道第二点,即调用函数时使用的指针很重要,即

// the second getX() in the above example.
getX()
// is equivalent to:
globalPointer.getX()

并且由于全局 x = 9 属于 globalPointer,所以结果是 9 而不是 81.

请帮我检查一下我的理解,欢迎正确的措辞或真实幕后逻辑。

Since the (first) getX belongs to the module object, it cannot be seen without the prefix module., so everyone knows that it should be module.getX()

这是不准确的。 getX 函数不 属于 对象 module。相反,module 对象有一个名为 getX 的 属性,它引用名为 getX 的函数对象。 getX 函数对象没有关于其存储位置的信息。

module 的对象初始化器被编译时,用于初始化 module.getX 的匿名函数值自动命名为被初始化的 属性。这就是 getX 函数对象如何将 name 属性 设置为“getX”。


But what causes confusion is that this of the (first) getX will also reference the pointer calling the (first) getX function.

函数内部代码看到的 this 值通常由 JavaScript 引擎(在编译时)在 运行 时间 确定对于箭头函数),并在调用时在函数的作用域链记录中提供 - 意思是 thisNOT 作为参数传递给函数。因此第一次调用 getX

module.getX()

编译成

  • 获取module

    的值
  • 调用 getX 并将其 module 作为其 this 值传递。

    Moved from comment:
    Using extra words, when executing module.getX(), a this value of module is passed to getX in its environment records, not as an argument.

var getX = module.getX

创建一个名为 getX 的全局变量并将其值设置为 module.getX 中保存的函数对象引用。当调用全局变量 getX 时,运行 时间引擎将全局对象作为 getX 在 运行 时看到的 this 值传递。


When I define the second (pointer to) function by var getX = module.getX, it helps us to keep seeing the first getX inside/of module.

只有在查看 module 的初始化程序的意义上才能看到 getX 的源代码。全局变量指向一个名为getXmodule.getX的函数对象独立指向同一个函数对象。但是,修改 module.getXvar getX 的值不会相互影响。


另请参阅