Skip to content

Instantly share code, notes, and snippets.

@Sljubura
Created March 5, 2013 19:08
Show Gist options
  • Save Sljubura/5093170 to your computer and use it in GitHub Desktop.
Save Sljubura/5093170 to your computer and use it in GitHub Desktop.
Factory pattern is soo simple in JavaScript
function CarMaker() {}
CarMaker.prototype.drive = function () {
return "Vroom, I have " + this.doors + " doors";
};
CarMaker.factory = function (type) {
var constr = type,
newcar;
if (typeof CarMaker[constr] !== "function") {
throw {
name: "Error",
message: constr + " doesn't exist"
};
}
if (typeof CarMaker[constr].prototype.drive !== "function") {
CarMaker[constr].prototype = new CarMaker();
}
newcar = new CarMaker[constr]();
return newcar;
};
CarMaker.Compact = function () {
this.doors = 4;
};
CarMaker.Convertible = function () {
this.doors = 2;
};
CarMaker.SUV = function () {
this.doors = 24;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment