DIV CSS 佈局教程網

擴充 JavaScript 功能的正確做法(譯文)
編輯:關於JavaScript     

在《JavaScript 每周導讀》第三期中看到一篇〈Extending JavaScript – The Right Way〉,覺得很實用,於是翻譯過來分享。以下並非逐字翻譯,而是盡量把觀念講得通俗好懂。

問題:直接掛 prototype 會汙染枚舉

JavaScript 內建了許多強大的方法,但偶爾還是會遇到需要的功能不存在。要優雅地擴充,示範一個 capitalize():把字串首字母大寫。最直覺的寫法如下:

if(!String.prototype.capitalize)
{
String.prototype.capitalize = function()
{
return this.slice(0,1).toUpperCase() + this.slice(1).toLowerCase();
}
}

功能完全正常。但如果某處有用 for-in 遍歷字串:

var strings = "yay";
for(i in strings) console.log(i + ":" + strings[i]);

輸出卻會多出意料之外的一行:

0: y
1: a
2: y
capitalize: function () { return this.slice(0, 1).toUpperCase() + this.slice(1).toLowerCase(); }

原因是我們新增的方法其 enumerable 屬性預設為 true,於是被 for-in 一併枚舉出來。

解法:用 defineProperty 把 enumerable 設為 false

if(!String.prototype.capitalize)
{
Object.defineProperty(String.prototype, 'capitalize',
{
value: function()
{
return this.slice(0,1).toUpperCase() + this.slice(1).toLowerCase();
},
enumerable: false
});
}

再跑一次同样的迴圈:

var strings = "yay";
for(i in strings) console.log(i + ":" + strings[i]);

輸出乾淨了:

0: y
1: a
2: y

要注意的是,「迴圈沒有輸出」不代表方法不存在:

var strings = "yay";
console.log(strings.capitalize)

仍然會印出:

function () { return this.slice(0, 1).toUpperCase() + this.slice(1).toLowerCase(); }

用這種方式擴充相當靈活,也能用來定義自己的物件並設定各種預設值。

幾個可以直接用在專案裡的擴充

String.pxToInt()——把 "200px" 轉成數字 200:

if(!String.prototype.pxToInt)
{
Object.defineProperty(String.prototype, 'pxToInt',
{
value: function()
{
return parseInt(this.split('px')[0]);
},
enumerable: false
});
}

String.isHex()——判斷是否為 16 進位色碼,如 #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()——字串反轉:

if(!String.prototype.reverse)
{
Object.defineProperty(String.prototype, 'reverse',
{
value: function()
{
return this.split('').reverse().join('');
},
enumerable: false
});
}

String.wordCount()——以空白切分統計單字數:

if(!String.prototype.wordCount)
{
Object.defineProperty(String.prototype, 'wordCount',
{
value: function()
{
return this.split(' ').length;
},
enumerable: false
});
}

String.stripTags()——移除 HTML 標籤:

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()——統計物件屬性數量,例如 {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
});
}

我的幾點補充

這種做法擴充原生物件確實不錯,但除非專案裡真的大量重複使用,否則不建議直接在原生物件上擴充,容易造成全域汙染與團隊間的衝突。

另外,文中的 pxToInt() 其實沒什麼必要,parseInt 本來就能勝任:parseInt("200px") === 200。

htmlEntities 的實作也怪怪的(原文那段程式碼在轉義上就有問題),改用 DOM 反而更可靠:

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
});
}

最後補充一個觀念:ES5 以前並沒有 Object.defineProperty(IE8 只支援 DOM 物件),所以在舊環境裡要避開 for-in 汙染,常見做法是改用 ES6 的 Symbol 作為方法名稱,或乾脆把工具函式收進 namespace 物件、不動原生 prototype。現在新建專案時,直接用 ES Module 匯出工具函式會是更乾淨的選擇。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved