gpt4 book ai didi

javascript - jQuery.proxy 与 underscore.bind

转载 作者:搜寻专家 更新时间:2023-11-01 04:09:34 24 4
gpt4 key购买 nike

在使用方法作为事件处理程序的上下文中(即 $(...).on('something', myObject.handleSomething))。我发现 $.proxy 和 _.bind ( http://jsperf.com/bind-vs-jquery-proxy/27 ) 之间的性能差异相对较大,并查看了它们的实现。

jQuery ( http://james.padolsey.com/jquery/#v=1.10.2&fn=proxy) 最终返回:

args = core_slice.call(arguments, 2);
proxy = function () {
return fn.apply(context || this, args.concat(core_slice.call(arguments)));
};

虽然下划线 ( http://underscorejs.org/docs/underscore.html#section-60) 最终返回(ctor 是 var ctor = function(){};):

args = slice.call(arguments, 2);
return bound = function() {
if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
ctor.prototype = func.prototype;
var self = new ctor;
ctor.prototype = null;
var result = func.apply(self, args.concat(slice.call(arguments)));
if (Object(result) === result) return result;
return self;
};

我知道 _.bind 将允许我为 new 调用绑定(bind)参数,但是如果我只想使用 它会有任何实际优势吗myObject.handleSomething 作为事件处理程序?

是否可以使用 $.proxy 编写类似于 _.bindAll 的内容?例如

$.proxyAll = function (obj) {
for (var attr in obj) if (obj.hasOwnProperty(attr) && $.isFunction(obj[attr])) {
obj[attr] = $.proxy(obj[attr], obj);
}
return obj;
};

最佳答案

您确定要衡量您关心的性能吗?

似乎您的测试用例正在测量绑定(bind)函数的性能,而此测试用例测量的是绑定(bind)函数的性能: http://jsperf.com/bind-vs-jquery-proxy/38

您应该只绑定(bind)函数有限(且相对较少)的次数,因此性能并不重要。这让我感到惊讶,但测量绑定(bind)函数的性能似乎会翻转结果。

另请注意,您的原始测试结果因浏览器而异。

关于javascript - jQuery.proxy 与 underscore.bind,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19056093/

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