Created
December 3, 2012 16:11
-
-
Save ryankinal/4195985 to your computer and use it in GitHub Desktop.
Some basic OO patterns for JS
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
| // factory | |
| var createObject = function(stuff) { | |
| var obj = {}; | |
| obj.stuff = stuff; | |
| obj.func = function() | |
| { | |
| return this.stuff + ' concatentation'; | |
| }; | |
| return obj; | |
| }; | |
| var obj = createObject('some stuff'); | |
| console.log(obj.func()); // 'some stuff concatenation' | |
| // pseudo-classical | |
| var CreateObject = function(stuff) | |
| { | |
| this.stuff = stuff; | |
| this.func = function() | |
| { | |
| return this.stuff + ' concatenation'; | |
| } | |
| } | |
| var obj = new CreateObject('some stuff'); | |
| console.log(obj.func()); // 'some stuff concatenation' | |
| // prototypal | |
| var base = { | |
| func: function() | |
| { | |
| return this.stuff + ' concatenation'; | |
| } | |
| } | |
| var obj = Object.create(base); | |
| obj.stuff = 'some stuff'; | |
| console.log(obj.func()); // 'some stuff concatenation' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment