原文地址:Extending JavaScript – The Right Way
以下是譯文
JavaScript已經(jīng)內(nèi)置了很多強(qiáng)大的方法,但有時(shí)你需要的某個(gè)功能在內(nèi)置的方法中沒(méi)有,我們?cè)趺磥?lái)優(yōu)雅地?cái)U(kuò)展JavaScript功能呢。
例如我們想增加一個(gè)capitalize()方法來(lái)實(shí)現(xiàn)首字母大寫,通常我們這樣寫:
代碼如下:
if(!String.prototype.capitalize)
{
String.prototype.capitalize = function()
{
return this.slice(0,1).toUpperCase() + this.slice(1).toLowerCase();
}
}
上面的代碼可以正常使用,但如果在某個(gè)地方有下面的代碼:
代碼如下:
var strings = "yay";
for(i in strings) console.log(i + ":" + strings[i]);
我們得到的結(jié)果是這樣的:
0: y
1: a
2: y
capitalize: function () { return this.slice(0, 1).toUpperCase() + this.slice(1).toLowerCase(); }
這顯然不是我們想要的結(jié)果,輸出了我們?cè)黾拥姆椒ǖ脑蚴俏覀冊(cè)黾拥姆椒ǖ膃numerable屬性默認(rèn)為true。
我們可以通過(guò)簡(jiǎn)單地把枚舉屬性(enumerable)設(shè)置為false避免這個(gè)問(wèn)題,使用defineProperty方法進(jìn)行功能的擴(kuò)展:
代碼如下:
if(!String.prototype.capitalize)
{
Object.defineProperty(String.prototype, 'capitalize',
{
value: function()
{
return this.slice(0,1).toUpperCase() + this.slice(1).toLowerCase();
},
enumerable: false
});
}
現(xiàn)在我們?cè)龠\(yùn)行這段代碼:
代碼如下:
var strings = "yay";
for(i in strings) console.log(i + ":" + strings[i]);
我們得到的結(jié)果是:
0: y
1: a
2: y
要注意的是,用循環(huán)沒(méi)有輸出的并不代表不存在,我們可以通過(guò)下面的代碼查看到定義:
代碼如下:
var strings = "yay";
console.log(strings.capitalize)
會(huì)輸出:
代碼如下:
function () { return this.slice(0, 1).toUpperCase() + this.slice(1).toLowerCase(); }
用這種方式擴(kuò)展JavaScript功能比較靈活,我們可以用這種方式來(lái)定義我們自己的對(duì)象,并設(shè)置一些默認(rèn)值。
以下是另外幾個(gè)擴(kuò)展方法,你可以在自己的項(xiàng)目中使用:
String.pxToInt()
把"200px"這樣的字符串轉(zhuǎn)換為數(shù)字 200 :
代碼如下:
if(!String.prototype.pxToInt)
{
Object.defineProperty(String.prototype, 'pxToInt',
{
value: function()
{
return parseInt(this.split('px')[0]);
},
enumerable: false
});
}
String.isHex()
判斷一個(gè)字符串是否是16進(jìn)制表示的,如"#CCC" 或 "#CACACA"
代碼如下:
if(!String.prototype.isHex)
{
Object.defineProperty(String.prototype, 'isHex',
{
value: function()
{
return this.substring(0,1) == '#' &&
(this.length == 4 || this.length == 7) &&
/^[0-9a-fA-F]+$/.test(this.slice(1));
},
enumerable: false
});
}
String.reverse()
字符串反轉(zhuǎn):
代碼如下:
if(!String.prototype.reverse)
{
Object.defineProperty(String.prototype, 'reverse',
{
value: function()
{
return this.split( '' ).reverse().join( '' );
},
enumerable: false
});
}
String.wordCount()
統(tǒng)計(jì)單詞數(shù)量,用空格分開
代碼如下:
if(!String.prototype.wordCount)
{
Object.defineProperty(String.prototype, 'wordCount',
{
value: function()
{
return this.split(' ').length;
},
enumerable: false
});
}
String.htmlEntities()
html標(biāo)簽如<和>編碼為特殊字符
代碼如下:
if(!String.prototype.htmlEntities)
{
Object.defineProperty(String.prototype, 'htmlEntities',
{
value: function()
{
return String(this).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"');
},
enumerable: false
});
}
String.stripTags()
去掉HTML標(biāo)簽:
代碼如下:
if(!String.prototype.stripTags)
{
Object.defineProperty(String.prototype, 'stripTags',
{
value: function()
{
return this.replace(/<\/?[^>]+>/gi, '');
},
enumerable: false
});
}
String.trim()
去掉首尾空格:
代碼如下:
if(!String.prototype.trim)
{
Object.defineProperty(String.prototype, 'trim',
{
value: function()
{
return this.replace(/^\s*/, "").replace(/\s*$/, "");
},
enumerable: false
});
}
String.stripNonAlpha()
去掉非字母字符:
代碼如下:
if(!String.prototype.stripNonAlpha)
{
Object.defineProperty(String.prototype, 'stripNonAlpha',
{
value: function()
{
return this.replace(/[^A-Za-z ]+/g, "");
},
enumerable: false
});
}
Object.sizeof()
統(tǒng)計(jì)對(duì)象的大小,如{one: “and”, two: “and”}為2
代碼如下:
if(!Object.prototype.sizeof)
{
Object.defineProperty(Object.prototype, 'sizeof',
{
value: function()
{
var counter = 0;
for(index in this) counter++;
return counter;
},
enumerable: false
});
}
這種方式擴(kuò)展JS原生對(duì)象的功能還是挺不錯(cuò)的,但除非必要(項(xiàng)目中用的很多),不建議直接在原生對(duì)象上擴(kuò)展功能,會(huì)造成全局變量污染。
另外,文中的pxToInt()方法是沒(méi)什么必要的,JS中的parseInt()可以直接完成這樣的功能:parsetInt("200px")===200
htmlEntities方法貌似有問(wèn)題,下面另提供一個(gè):
代碼如下:
if(!String.prototype.htmlEntities)
{
Object.defineProperty(String.prototype, 'htmlEntities',
{
value: function()
{
var div = document.createElement("div");
if(div.textContent){
div.textContent=this;
}
else{
div.innerText=this;
}
return div.innerHTML;
},
enumerable: false
});
}
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com