3

大多数具有枚举器方法的库(我认为甚至是原生 JavaScript)都允许context为迭代器传递 a 。

function reduce(iterator, memo, context){
    this.each(function(item, idx, list){
        memo = iterator.call(context, memo, item, idx, list)
    });
    return memo;
}

问题是为什么什么时候bind可以轻松提供相同的功能?

stooges.reduce(function(memo, stooge){
  ...
}, context) // as argument vs...

stooges.reduce(function(memo, stooge){
  ...
}.bind(context))

这是暂时存在的东西,因为bind并非在所有平台上都可用吗?或者仅仅是因为 ing 的开销callbinding 少?我总是读到,函数采用的参数越少越好。也就是说,一个函数取 0 参数比一个取 1 好于一个取 2,等等。

4

1 回答 1

2

使用.bind创建并返回一个新函数。在某些情况下,您更喜欢限制 javascript VM 创建的对象/变量的数量,以便利用垃圾收集器清理周期。

此外,bind已知比“模拟”绑定解决方案(使用calland apply)要慢得多:为什么 Function.prototype.bind 慢?

否则,将上下文作为参数传递通常会更好、更易读。

ES6 箭头函数将允许保持 lexical this,所以它会更容易:

// considering object context
var self = this;
stooges.reduce((memo, stooge) => (this === self));
于 2013-06-28T02:52:20.717 回答