考慮下面的代碼,使用ECMAScript5的Object.defineProperty
功能:周圍IE8的破Object.defineProperty實施工作
var sayHi = function(){ alert('hi'); };
var defineProperty = (typeof Object.defineProperty == 'function');
if (defineProperty) Object.defineProperty(Array.prototype,'sayHi',{value:sayHi});
else Array.prototype.sayHi = sayHi;
var a = [];
a.sayHi();
這適用於Chrome和Firefox 4(defineProperty
存在),它適用於火狐3.6(其中defineProperty
不存在)。 IE8,但是,only partially supports defineProperty
。因此,它嘗試運行Object.defineProperty
方法,但後來失敗(瀏覽器中未顯示錯誤),並停止運行頁面上的所有其他JavaScript代碼。
是否有更好的方法來檢測和避免IE8的碎實現比:
if (defineProperty){
try{ Object.defineProperty(Array.prototype,'sayHi',{value:sayHi}); }catch(e){};
}
if (!Array.prototype.sayHi) Array.prototype.sayHi = sayHi;
對於好奇,我使用這在我ArraySetMath庫來定義這些瀏覽器不可枚舉陣列中的方法支持這一點,爲舊版瀏覽器提供可枚舉的方法。