Created
March 5, 2013 19:08
-
-
Save Sljubura/5093170 to your computer and use it in GitHub Desktop.
Factory pattern is soo simple in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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