Module
模块可以提供一个接口,并且隐藏其中的状态与实现的的函数或者对象,利用模块我们可以完全屏蔽全局变量的使用(全局变量太坑了,55555)
A small example
Function.prototype.method = function(name,func){ this.prototype[name] = func; return this;}String.method("def",function(){ var ent = { quot:‘""‘, lt:‘<‘, gt:‘>‘ }; //这里的整个匿名自执行函数是window调用的 //this---->window return function(){ return this.replace(/&([^&;]+);/g,function(a,b){ var r = ent[b]; return typeof r ==="string" ? r : b; }); };}());/**************test*********************/var a = "<">".def();console.log(a);//<"">
In the custom Def property of string, this property is a self-executing function, it will return a new function and assign a value to Def (compare around ...), this new function is the final Def method added in string, only he has the right to access the internal ENT object
A single-case pattern
Look at another example of generating a key
<!-- lang: js -->//模块生成安全的对象var serial_maker = function (){ var prefix = ""; var seq = 0; return { set_seq:function(s){ seq = s; }, set_pre:function(p){ prefix = p; }, gensym:function(){ var result = prefix + seq; seq += 1; return result; } }}var seqer = serial_maker();seqer.set_pre("W");seqer.set_seq(100);console.log(seqer.gensym());//W100console.log(seqer.gensym());//W101console.log(seqer.gensym());//W102
Here is the return of an object, the property of this object is a function, these functions can access the variables defined in the Serial_maker, and the outside is unable to modify the value in the Serial_maker variable, Serial_maker return the value is unique
Ps
Module is the important idea of JavaScript programming, in fact, in many cases, I feel that the use of modules is a better choice, not necessarily with the object-oriented thinking, a lot of frameworks are built on the basis of the module, such as jquery, using the framework of object-oriented, internal implementation of the module using the model, The effect of the comparison is that jquery is part of the deferred object and callback function, and the internal method of using the module is implemented
Modules in the initial JavaScript