Last active
August 29, 2015 14:14
-
-
Save dgowrie/24fb3483051579b89512 to your computer and use it in GitHub Desktop.
"Class" like structure for JavaScript - a hybrid of the Module Pattern (a locally scoped object variant) and the Prototype Pattern... similar in result to the 'standard' (if such a thing) "Revealing Prototype Pattern"
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
| // "Class" like module pattern | |
| (function (NS) { | |
| 'use strict'; | |
| // constructor for the Person "Class", attached to global namespace | |
| var Person = NS.Person = function (name) { | |
| this.name = name; | |
| }; | |
| // may not be necessary, but safe | |
| Person.prototype.constructor = Person; | |
| // private method | |
| var _privateMethod = function() { | |
| // do private stuff | |
| // use the "_" convention to mark as private | |
| // this is scoped to the modules' IIFE wrapper, but not bound the returned "Person" object, i.e. it is private | |
| }; | |
| // public method | |
| Person.prototype.speak = function() { | |
| console.log("Hello there, I'm " + this.name); | |
| }; | |
| return Person; | |
| })(window.NS = window.NS || {}); | |
| // use your namespaced Person "Class" | |
| var david = new NS.Person("David"); | |
| david.speak(); |
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
| // and a variant more along the lines of the 'standard' Revealing Prototype Pattern | |
| (function (NS) { | |
| 'use strict'; | |
| // constructor for the Person "Class", attached to global namespace | |
| var Person = NS.Person = function (name) { | |
| // reset constructor (the prototype is completely overwritten below) | |
| this.constructor = Person; | |
| // set properties unique for each instance | |
| this.name = name; | |
| }; | |
| // all methods on the prototype | |
| Person.prototype = (function() { | |
| // private method | |
| var _privateMethod = function() { | |
| // do private stuff | |
| // use the "_" convention to mark as private | |
| // this is scoped to the IIFE but not bound to the returned object, i.e. it is private | |
| }; | |
| // public method | |
| var speak = function() { | |
| console.log("Hello there, I'm " + this.name); | |
| }; | |
| // returned object with public methods | |
| return { | |
| speak: speak | |
| }; | |
| }()); | |
| })(window.NS = window.NS || {}); // import global namespace | |
| // use your namespaced Person "Class" | |
| var david = new NS.Person("David"); | |
| david.speak(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment