javascript Module

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 16:05   1165   0

模块=函数+闭包构成,一个模块是用一个对象或函数来表示的一个接口,并隐藏了属性和方法。通过使用函数去产生模块,我们可以完全不用全局变量,因此可以缓解JavaScript’s 最糟糕的特征之一。
例如:假设我们想在String对象增加一个 deentityify()方法 它的工作在HTML里寻找在字符串里的实体,然后用对应的值替换他们,在一个对象里,保存实体名字和他们对应的值,是有意义。但是我们把对象保存在哪里呢?我们要放在一个全局变量里,但是全局变量不好,我们能放在函数里面?但是有运行时成本,每当函数被调用时固定值必须被计算,理想的方法是放到闭包里,也许提供一特别的方法增加实体。

String.method('deentityify', function ( ) {
// The entity table. It maps entity names to
// characters.
var entity = {
quot: '"',
lt: '<',
gt: '>'
};
// Return the deentityify method.
return function ( ) {
// This is the deentityify method. It calls the string
// replace method, looking for substrings that start
// with '&' and end with ';'. If the characters in
// between are in the entity table, then replace the
// entity with the character from the table. It uses
// a regular expression (Chapter 7).
return this.replace(/&([^&;]+);/g,
function (a, b) {
var r = entity[b];
return typeof r === 'string' ? r : a;
}
);
};
}());




Notice the last line. We immediately invoke the function we just made with the( )
operator. That invocation creates and returns the function that becomes the
deentityify method.

document.writeln(
'<">'.deentityify( )); // <">


The module pattern takes advantage of function scope and closure to create relationships that are binding and private. In this example, only thedeentityify method has
access to the entity data structure.
The general pattern of a module is a function that defines private variables and functions; creates privileged functions which, through closure, will have access to the private variables and functions; and that returns the privileged functions or stores them in an accessible place.

Use of the module pattern can eliminate the use of global variables. It promotes
information hiding and other good design practices. It is very effective in encapsulating applications and other singletons.
It can also be used to produce objects that are secure. Let’s suppose we want to make
an object that produces a serial number:





分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP