考虑以下代码,使用ECMAScript5的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
存在),也适用于Firefox 3.6(其中defineProperty
不存在)。然而,IE8 仅部分支持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库中使用它来定义非枚举数组方法,以便在支持这一特性的浏览器中使用,对于旧浏览器则回退到枚举方法。