jQuery.proxy与underscore.bind

the*_*orn 5 javascript jquery underscore.js

在使用方法作为事件处理程序(即$(...).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)));
};
Run Code Online (Sandbox Code Playgroud)

而下划线(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;
};
Run Code Online (Sandbox Code Playgroud)

我明白这_.bind将允许我绑定一个new调用的参数,但如果我只想myObject.handleSomething用作事件处理程序,它会有任何实际的优势吗?

是否有可能写出类似于_.bindAll使用的东西$.proxy?例如

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

col*_*lin 5

你确定你在衡量你关心的表现吗?

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

你应该只绑定函数有限(和相对较小)的次数,所以性能并不重要.这对我来说是一个惊喜,但测量绑定函数的性能似乎可以推翻结果.

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

  • 接得好.(基准测试不是我的,但我在研究绑定实现时发现了一个链接).我已经使用了一系列我可用的浏览器来运行基准测试,并添加了版本39,我还添加了本机绑定. (2认同)