Last Updated: February 25, 2016
·
370
· 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);

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside