Created
January 3, 2012 19:54
-
-
Save ValeriiVasin/1556603 to your computer and use it in GitHub Desktop.
[javascript patterns] Factory.
This file contains hidden or 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
| var CarMaker = function () {}; | |
| CarMaker.prototype.introduce = function () { | |
| console.log("This is " + this.title); | |
| }; | |
| CarMaker.factory = function (type) { | |
| var constr = type, | |
| newcar; | |
| if (typeof CarMaker[constr] !== 'function') { | |
| throw { | |
| name: 'Error', | |
| message: "Constr " + constr + "doesn't exist" | |
| }; | |
| } | |
| if (typeof CarMaker[constr].prototype.introduce !== 'function') { | |
| CarMaker[constr].prototype = new CarMaker(); | |
| } | |
| newcar = new CarMaker[constr](); | |
| return newcar; | |
| }; | |
| CarMaker.Daewoo = function () { | |
| this.title = "Daewoo"; | |
| }; | |
| CarMaker.Ford = function () { | |
| this.title = "Ford"; | |
| }; | |
| // usage | |
| var daewoo = CarMaker.factory('Daewoo'); | |
| daewoo.introduce(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment