为什么使用绑定函数 (javascript) 后属性未定义?

Why are properties undefined after using bind function (javascript)?

这是 link 对 function.prototype.bind() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

的 MDN 解释

我添加了一些 console.logs 来帮助我理解发生了什么。

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

var boundGetX = module.getX.bind(module);

console.log(boundGetX());
console.log(boundGetX().x);
console.log(boundGetX.x);

第console.logreturns

42

这对我来说很有意义。

然而,第二个和第三个console.logsreturn

undefined

这是为什么?该函数如何能够查看和记录模块 属性、x,其存储值为 42,而 x 的 boundGetX 值未定义?

使用绑定函数后,boundGetX 不是指向 module.getX 并且 'this' 变量指向模块吗?

为什么 boundGetX.x 不指向 module.x?当 boundGetX.x 未定义时,它如何能够成功记录 module.x 的值?

当你打电话时:

console.log(boundGetX().x);

您实质上是在调用:

this.x.x

实际在做什么:

(42).x // there's no property x on the number 42

并且由于 属性 x 上没有 属性 x,所以它是 undefined

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

bind function 更改了 this 的含义,在您的情况下,您设置 module 以在 getX 函数中解析为 this

getX: function() {
   return this.x;   // <-- this is now `module` object so `x` resolves to 42
}

这就是 console.log(boundGetX()); 现在打印 42 的原因,因为您实际上是通过 module.getX 函数打印 module.x

现在这两个:

console.log(boundGetX().x);
console.log(boundGetX.x);

没有任何意义,因为您将 boundGetX 绑定到 getX 函数并且该函数没有 x 属性 也没有 returns x 属性,它只是 returns x 的 值。