javascript Module

  模块=函数+闭包构成,一个模块是用一个对象或函数来表示的一个接口,并隐藏了属性和方法。通过使用函数去产生模块,我们可以完全不用全局变量,因此可以缓解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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值