2011年2月11日金曜日

Function.prototype.bind and Constructor

using Function.prototype.bind, dispatch arguments to [[Construct]]

Object.defineProperties(Function.prototype, {
  'applyConstructor': {
    enumerable: false,
    configurable: true,
    writable: true,
    value: function applyConstructor(list) {
      var args = Array.prototype.slice.call(list);
      args.unshift(null); // dummy
      var Bound = this.bind.apply(this, args);
      return new Bound();
    }
  },
  'callConstructor': {
    enumerable: false,
    configurable: true,
    writable: true,
    value: function callConstructor() {
      var args = Array.prototype.slice.call(arguments);
      args.unshift(null);  // dummy
      var Bound = this.bind.apply(this, args);
      return new Bound();
    }
  }
});
and, create Factory Pattern.
function Test(a, b) {
  this.a = a;
  this.b = b;
}
Test.create = Test.callConstructor.bind(Test);
and use it.
var test = Test.create(10, 20);
test.test();

This entry is posted first at my blog