/ Published in: JavaScript
"Javascript module pattern emulates the concept of classes in such a way that we're able to include both public/private methods and variables inside a single object, thus shielding/namespacing particular parts from the global scope."
When inheritance is not needed and a only few instances is needed (Keep in mind that each instance places a new copy of each function in memory!)
When inheritance is not needed and a only few instances is needed (Keep in mind that each instance places a new copy of each function in memory!)
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/* The idea here is that you have private methods which you want to expose as public methods. */ var SomeModule = (function(param){ // Private stuff // 'this' keyword refers to the current instance. Must use 'new' when creating instances of the module, else 'this' will refer to global scope. this.initval = param; this.name = 'John Smith'; this.age = 40; function setPerson(param) { this.name = param; } function getPerson() { return this.name; // create closure (inner function) to bind the var (= keep it around) } // Public stuff / reveal and bind return { set: this.setPerson, get: this.getPerson, age: this.age }; }); // creating instances var newModule = new SomeModule(newparam); newModule.set("Some Name"); var name = newModule.age; var name = newModule.get;
URL: http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#designpatternsjavascript