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的開銷。模塊化的重要有必要單獨寫一篇總結。

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