5

在使用方法作为事件处理程序的上下文中(即$(...).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 is 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调用绑定参数,但如果我只想myObject.handleSomething用作事件处理程序,它会有任何实际优势吗?

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

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

1 回答 1

5

你确定你正在衡量你关心的性能吗?

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

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

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

于 2014-02-19T19:04:19.057 回答