【问题标题】:Avoiding .call() and .apply() using .bind()使用 .bind() 避免 .call() 和 .apply()
【发布时间】:2012-05-02 03:10:24
【问题描述】:

我正在寻找一种方法来完成某项任务,即从

jQuery.when.apply( null, promiseArray ).done(...)

when( promiseArray ).done(...)

您可能知道,.bind() 可以用来创建类似默认参数的东西,也可以做一些非常漂亮的事情。例如,而不是总是调用

var toStr = Object.prototype.toString;
// ...
toStr.call([]) // [object Array]

我们可以这样做

var toStr = Function.prototype.call.bind( Object.prototype.toString );
toStr([]) // [object Array]

这很酷(即使有像这样调用.bind() 的性能惩罚,我知道并且我知道它),但我无法真正为jQuerys .when 调用完成它。如果你有未知数量的 Promise 对象,你通常会将它们推送到一个数组中,然后能够将它们传递到 .when 中,就像我在上面的第一个代码 sn-p 中一样。

到目前为止我正在这样做:

var when = Function.prototype.apply.bind( $.when );

现在我们可以去

when( null, promiseArray ).done(...)

这行得通,但我也想摆脱每次都明确传递null 的需要。所以我尝试了

var when = Function.prototype.apply.bind( $.when.call.bind( null ) );

但这让我很困惑:

"TypeError: Function.prototype.apply called on incompatible null"

我想我现在在这个问题上坐得太久了,不能再思考了。感觉有一个简单的解决方案。 我不想使用任何额外的功能来解决这个问题,我绝对更喜欢使用.bind()的解决方案。

在此处查看完整示例:http://jsfiddle.net/pp26L/

【问题讨论】:

  • @Raynos: 是的,把盐擦进我受伤的自我……:p

标签: javascript jquery ecmascript-5


【解决方案1】:

这应该可行:

when = Function.prototype.apply.bind( $.when, null);

您只需绑定(或 curry,如果您愿意).bind 的第一个参数并将其修复为 null

Fiddle.

【讨论】:

  • 天哪,我很确定我在某个时候做到了。我怎么能错过呢?至少我知道这是一个大问题的相当简单的解决方案。谢谢@Jon!
  • @jAndy:考虑到你的JS排骨比我好多了,很明显你因为疲劳而错过了。干杯。
【解决方案2】:

bind 接受可变数量的参数,因此您可以部分应用方法。所以,而不是:

var when = Function.prototype.apply.bind( $.when );

这样做:

var when = Function.prototype.apply.bind( $.when , null );

并更新了 jsfiddle:http://jsfiddle.net/pp26L/2/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-07
    • 2012-07-12
    • 1970-01-01
    • 2022-11-13
    相关资源
    最近更新 更多