JavaScript 编程珠玑 - 《JavaScript: The good parts》总结(2)

一、扩展函数原型的更好办法:

// 定义下面的通用方法
Function.prototype.method = function (name, func) {
    this.prototype[name] = func;
    return this;
};
// 使用上面的通用方法作为工具进行扩展,以免每次扩展都访问Function.prototype.XXX (that's ugly).
Number.method('integer', function() {
    return Math[this < 0 ? 'ceil' : 'floor'](this);
}
document.writeln((-10 / 3).integer()); // -3

如果给String增加方法,只需String.method('newFun', function(){...})。从上面例子也可以看到[]获取属性带来的好处, Math['ceil'](n) 等价于 Math.ceil(n),但前者属性名可以是变量。


二、闭包(Closure) 

var myObject = (function ( ) {
    var value = 0;
    return {
        increment: function (inc) {
            value += typeof inc === 'number' ? inc : 1;
        },
        getValue: function ( ) {
            return value;
        }
    };
}());

上面将匿名函数的执行结果付给myObject,使其具有increment和getValue属性,从而隐藏了value.


三、模块(Module)

模块是隐藏内部实现细节,暴露接口的好方法。JavaScript中常使用function来实现模块化。如jQuery和node.js中有很多好例子。

String.method('deentitify', function () {
    var entity = {
        quot: '"',
        lg: '<',
        gt: ''        
    };
    
    return function() {
        return this.replace(/&([^&;]+);/g,
            function (a,b) {
                var r = entity[b];
                return r === 'string' ? r : a;
            }
        };
    };
}());

上面的用法既隐藏了entity这个细节实现,又避免了每次调用都实例化entity的开销。模块化的重要有必要单独写一篇总结。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章