gpt4 book ai didi

javascript - 使用新参数将函数重新绑定(bind)到原始绑定(bind)对象

转载 作者:行者123 更新时间:2023-12-03 03:17:51 25 4
gpt4 key购买 nike

是否可以重新绑定(bind)函数,使其绑定(bind)到原来的同一对象,但接受不同的参数值?

例如...

// Object definition
function OriginalOwner(prop) { this.prop = prop; }
OriginalOwner.prototype.aFunc = function(arg) { return this.prop + arg; }

// Object instance
var owner = new OriginalOwner("Returned ");

// Example function bindings
var boundFunc = owner.aFunc.bind(owner);
var reboundFunc = boundFunc.bind(boundFunc.owner, "myArgument");

// Calling rebound function
console.log(reboundFunc()); // outputs "Returned myArgument"

最佳答案

如果您只想添加参数,可以使用bind来实现。为第一个 bind 参数提供什么并不重要,因为当您在绑定(bind)函数上调用 bind 时,它将被忽略(因此 null > 是第一个参数的合理选择)。

由于第一个参数被忽略,您的原始代码将保持不变,但会产生误导(boundFunc 没有 owner 属性,因此 boundFunc.owner 产生未定义)。但最好使用 null 或其他东西,以避免稍后阅读代码的人误读。

唯一的变化是格式和缺少 ;,加上 *** 行:

// Object definition
function OriginalOwner(prop) {
this.prop = prop;
}
OriginalOwner.prototype.aFunc = function(arg) {
return this.prop + arg;
};

// Object instance
var owner = new OriginalOwner("Returned ");

// Example function bindings
var boundFunc = owner.aFunc.bind(owner);
var reboundFunc = boundFunc.bind(null, "myArgument"); // ***

// Calling rebound function
console.log(reboundFunc()); // outputs "Returned myArgument"

有效的原因bind返回一个新函数,该函数将使用我们提供的this来调用——但是我们绑定(bind)的函数调用它完全忽略您调用它的 this,而是使用 it 绑定(bind)到它的那个。

关于javascript - 使用新参数将函数重新绑定(bind)到原始绑定(bind)对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46691899/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com