Created
January 14, 2014 02:05
-
-
Save dasjestyr/8411820 to your computer and use it in GitHub Desktop.
Examples of various OOP-ish type object patterns in Javascript
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
| // Example of constructor pattern | |
| function Person(firstName, lastName){ | |
| this.firstName = firstName; | |
| this.lastName = lastName; | |
| this.introduceSelf = function(){ | |
| alert('Hello, my name is ' + this.firstName + ' ' + this.lastName + '.'); | |
| } | |
| } | |
| // usage | |
| var me = new Person('Jeremy', 'Stafford'); | |
| me.introduceSelf(); | |
| // Example of object literal (emulates a public static class) | |
| var MyClass = { | |
| firstName: 'Jeremy', | |
| lastName: 'Stafford', | |
| introducePerson: function(person){ | |
| alert('Hello, my name is ' + person.firstName + ' ' + person.lastName + '.'); | |
| } | |
| } | |
| // usage | |
| var me = new Person('Jeremy', 'Stafford'); | |
| MyClass.introducePerson(me); | |
| // Example of Module pattern (emulates a class) | |
| var MyPerson = (function(){ | |
| // encapsulated values | |
| var counter = 0; | |
| // functional object | |
| return { | |
| incrementCounter: function(){ | |
| return counter++; | |
| }, | |
| resetCounter: function(){ | |
| alert('Counter was reset'); | |
| counter = 0; | |
| } | |
| } | |
| })(); | |
| // usage | |
| alert(MyPerson.incrementCounter()); | |
| // simplified explanation of modul pattern | |
| var foo = (function(){ | |
| // private members | |
| var theNumber = 0 | |
| function incrementTheNumber(){ | |
| theNumber++; | |
| }; | |
| return { | |
| // public members | |
| className: 'foo', | |
| getNext: function(){ | |
| incrementTheNumber(); | |
| return theNumber; | |
| } | |
| } | |
| })(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment