【问题标题】:Why are properties undefined after using bind function (javascript)?为什么使用绑定函数(javascript)后属性未定义?
【发布时间】:2018-12-09 18:52:25
【问题描述】:

这里是function.prototype.bind()的MDN解释链接-https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

我添加了一些 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.log返回

42

这对我来说很有意义。

但是,第二个和第三个console.logs返回

undefined

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

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

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

【问题讨论】:

    标签: javascript pointers undefined bind


    【解决方案1】:

    当你打电话时:

    console.log(boundGetX().x);
    

    你实际上是在打电话:

    this.x.x
    

    实际上在做什么:

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

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

    【讨论】:

    • 好的。我想我明白了。谢谢。
    【解决方案2】:

    bind() 方法创建一个新函数,在调用该函数时,该函数具有 this 关键字设置为提供的值,具有给定的序列 调用新函数时提供的任何参数之前的参数。

    bind function 改变了this 的含义,在您的情况下,您在getX 函数中将module 设置为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 属性也不返回 x 属性,它只是返回一个 x 的值.

    【讨论】:

    • 谢谢。这很有帮助。
    猜你喜欢
    • 2012-01-10
    • 1970-01-01
    • 2013-05-21
    • 2018-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-30
    • 2022-01-14
    相关资源
    最近更新 更多