Javascript模块模式模板
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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!)
/* 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;
以上是关于Javascript模块模式模板的主要内容,如果未能解决你的问题,请参考以下文章