【问题标题】:Re-bind function with new arguments to originally bound object使用新参数将函数重新绑定到最初绑定的对象
【发布时间】:2017-10-11 15:14:31
【问题描述】:

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

比如……

// 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"

【问题讨论】:

标签: javascript


【解决方案1】:

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

因为第一个参数被忽略,您的原始代码将保持不变,但它会产生误导(boundFunc 没有owner 属性,所以boundFunc.owner 产生undefined)。但最好使用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 调用 - 但我们调用它的绑定函数完全忽略了 @987654336 @ 你调用它,使用 it 绑定到它的那个。

【讨论】:

  • 我很确定术语“绑定函数”被用作“方法绑定到接收器”,而不是“方法绑定了接收器”。
  • @Bergi:我不确定你想说什么。绑定函数有一个特定的 this 值绑定到它。它在 [[BoundThis]] 内部插槽中 - @987654321 @.
  • 我的意思是“绑定函数”是绑定到对象的函数,而不是反过来(对象绑定到函数)。当然,最终它们是“绑定 together”,所以可能两种方式都可以使用,但 imo 使用“绑定到 BoundFunction 实例的 [[BoundThis]]”很奇怪。
  • @Bergi:嗯,“这个函数有一个特定的this 绑定到它”是有道理的,并且是真的/符合规范,所以对我来说一点也不奇怪。但我确实明白你在说相反的意思,FWIW。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-21
  • 1970-01-01
  • 2017-12-05
  • 2013-01-31
  • 2021-11-09
  • 2011-05-01
相关资源
最近更新 更多