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 は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

_.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;
};
4

1 に答える 1