gpt4 book ai didi

javascript - 使用 .bind() 避免 .call() 和 .apply()

转载 作者:可可西里 更新时间:2023-11-01 01:32:02 24 4
gpt4 key购买 nike

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

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 中,就像我在上面的第一个代码片段中那样。

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

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/

最佳答案

这应该有效:

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

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

Fiddle .

关于javascript - 使用 .bind() 避免 .call() 和 .apply(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10247807/

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