老版本 IE (6-8) 缺少 ES5/ES6 標準方法,通過原型擴展可實現兼容,但需注意**不要污染原型鏈**與**避免覆蓋原生實現**。
if (!String.prototype.startsWith) {
String.prototype.startsWith = function(searchStr, position) {
position = position || 0;
return this.slice(position, position + searchStr.length) === searchStr;
};
}
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(searchElement, fromIndex) {
var len = this.length >>> 0;
fromIndex = +fromIndex || 0;
if (fromIndex < 0) fromIndex = Math.max(len + fromIndex, 0);
for (; fromIndex < len; fromIndex++) {
if (fromIndex in this && this[fromIndex] === searchElement) return fromIndex;
}
return -1;
};
}
if (!Array.prototype.contains) {
Array.prototype.contains = function(item) {
return this.indexOf(item) !== -1;
};
}
if (!Array.prototype.xxx)),避免覆蓋原生高效實現。Object.defineProperty 設置 enumerable: false,防止 for...in 遍歷污染。
Object.defineProperty(Array.prototype, 'contains', {
value: function(item) { return this.indexOf(item) !== -1; },
writable: true, configurable: true, enumerable: false
});core-js 或 babel-polyfill**,統一由構建工具按目標環境注入 polyfill,手動擴展僅作舊專案維護。String.prototype.trim (ES5)if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
};
}