js對象常量定義函數(shù)&&鏈模式(筆記)

var constant = (function() {
    var constants = {}, //存儲已經(jīng)定義過的屬性
        ownProp = Object.prototype.hasOwnProperty, //檢查對象屬性是否存在
        allowned = {  //允許定義的常量值數(shù)據(jù)類型
            string: 1,
            number: 1,
            boolean: 1
        },
        prefix = (Math.random() + '_').slice(2);  //給定義的常量值檢測添加的隨機值,保證聲明的常量值不會與內(nèi)置屬性沖突
    return {
        //檢測定義的常量值是否存在
        isDefined: function(name) {
            return ownProp.call(constants, prefix + name);
        },
        //定義常量值
        set: function(name, value) {
            if(this.isDefined(name)) {return false;}
            if(!ownProp.call(allowned, typeof value)) {return false;}
            constants[prefix + name] = value;
            return true;
        },
        //獲取常量值
        get: function(name) {
            if(this.isDefined(name)) {
                //如果定義了就返回
                return constants[prefix + name];
            }
            return null;
        }
    }
})();
constant.isDefined('maxwidth')
false
constant.set('maxwidth', 480)
true
constant.isDefined('maxwidth')
true

鏈模式可以一個接一個的調(diào)用對象的方法。當(dāng)創(chuàng)建的方法返回的是無任何意義的值時,可以使他們返回this(正在調(diào)用的對象的實例)。

var obj = {
    value: 1,

    increment: function() {
        this.value += 1;
        return this;
    },
    add: function(v) {
        this.value += v;
        return this;
    },
    shou: function() {
        alert(this.value);
    }
}
obj.increment().add(3).shou(); //5

優(yōu)點: 創(chuàng)建簡潔的代碼,使得代碼優(yōu)美;可以幫助分割函數(shù),創(chuàng)建更加簡潔具有特定功能的函數(shù),而不創(chuàng)建太多功能函數(shù),長遠來看,提高了代碼的課維護性。
缺點: 調(diào)試困難,當(dāng)鏈中多個方法的其中一個出現(xiàn)錯誤,無法知道哪一個方法錯誤。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容