绕过IE8的Object.defineProperty实现的问题
- 论坛
- 绕过IE8的Object.defineProperty实现的问题
12 浏览
绕过IE8的Object.defineProperty实现的问题
考虑以下代码,使用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库中使用这个来定义非可枚举的数组方法,以在支持的浏览器中使用,对于旧版本的浏览器则使用可枚举的方法作为备用。