Last Updated: February 25, 2016
·
160
· vii

A factory method for JS class

function Ctor(param1, param2, param3) {
  this._param1 = param1;
  this._param2 = param2;
  this._param3 = param3;
}

// Factory method \w set parameters
Ctor.create = function(p1, p2, p3) {
  return new this(p1, p2, p3);
}

// True factory method
Ctor.factroy = function() {
  var instance = Object.create(Ctor.prototype);
  return Ctor.apply(instance, arguments) || instance;
}

Usage:

var c = Ctor.create(1, 2, 3);
console.log('c', c, c.create);
console.assert(c instanceof Ctor);

var cf = Ctor.factroy(1, 2, 3);
console.log('cf', cf, cf.create);
console.assert(cf instanceof Ctor);