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)錯誤,無法知道哪一個方法錯誤。