【问题标题】:Javascript Rebinding An Bound Founction [duplicate]Javascript重新绑定绑定函数[重复]
【发布时间】:2015-10-25 03:31:30
【问题描述】:

说我有sn-p

function hi() {
    console.log('Hello ' + this._hi);
}

var marcie = hi.bind({_hi: 'Sir'});
var patty = marcie.bind({_hi: 'Lucille'});

marcie(); // output: Hello Sir
patty(); // expected: Hello Lucille // actual: Hello Sir

我想重新绑定绑定的函数ma​​rcie,但看起来重新绑定不起作用。

我知道在更改函数上下文时 callapplybind。但是当它已经绑定时,它似乎不起作用。

如何在 javascript 中重新绑定绑定的函数? 还是不允许?

【问题讨论】:

    标签: javascript


    【解决方案1】:

    当您使用bind 时,您会得到一个新函数,它是某种代理:当您调用该代理时,它会忽略传递的this,并使用绑定的this 调用原始函数。

    因此:

    • hithis 做了一些事情
    • marcie 忽略其 this 并调用 hi{_hi: 'Sir'} 作为 this
    • patty 忽略其 this 并调用 marcie{_hi: 'Lucille'} 作为 this

    但是,由于marcie 忽略了this,所以patty 没用。

    相反,您应该始终在原始函数上使用bind

    function hi() {
      return 'Hello ' + this._hi;
    }
    var marcie = hi.bind({_hi: 'Sir'}),
        patty = hi.bind({_hi: 'Lucille'});
    [marcie(), patty()]; // ["Hello Sir", "Hello Lucille"]
    
    • hithis 做某事
    • marcie 忽略它的 this 并调用 hi{_hi: 'Sir'} 作为 this
    • patty 忽略其 this 并调用 hi{_hi: 'Lucille'} 作为 this

    【讨论】:

    猜你喜欢
    • 2018-11-10
    • 2012-12-11
    • 1970-01-01
    • 2022-06-22
    • 1970-01-01
    • 2013-02-08
    • 2013-08-23
    • 2010-09-14
    • 2016-08-21
    相关资源
    最近更新 更多