问题描述
使用ECMAScript5的 Object.defineProperty
功能考虑以下代码:
Consider the following code, using ECMAScript5's Object.defineProperty
feature:
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
exists),适用于Firefox 3.6(其中 defineProperty
不存在)。但是,IE8 。因此,它尝试运行 Object.defineProperty
方法,但随后失败(浏览器中未显示错误)并停止在页面上运行所有其他JavaScript代码。
This works for Chrome and Firefox 4 (where defineProperty
exists), and it works for Firefox 3.6 (where defineProperty
does not exist). IE8, however, only partially supports defineProperty
. As a result, it attempts to run the Object.defineProperty
method, but then fails (with no error shown in the browser) and ceases to run all other JavaScript code on the page.
有没有更好的方法来检测和避免IE8的实施中断:
Is there a better way to detect and avoid IE8's broken implementation than:
if (defineProperty){
try{ Object.defineProperty(Array.prototype,'sayHi',{value:sayHi}); }catch(e){};
}
if (!Array.prototype.sayHi) Array.prototype.sayHi = sayHi;
对于好奇,我在库,用于在支持此功能的浏览器中定义不可枚举的数组方法,并回退旧版浏览器的可枚举方法。
For the curious, I'm using this in my ArraySetMath library to define non-enumerable array methods in those browsers that support this, with a fallback to enumerable methods for older browsers.
推荐答案
我认为没有比使用try / catch进行直接功能测试更好的方法。这实际上正是IE团队在最近的帖子中推荐的。
I don't think there's a better way than a direct feature test with try/catch. This is actually exactly what IE team itself recommends in this recent post on transitioning to ES5 API.
您可以将测试缩短为类似 Object.defineProperty({},'x',{})
(而不是使用 Array.prototype
),但这是一个小狡辩;您的示例测试了确切的功能(因此误报的可能性更小)。
You can shorten the test to just something like Object.defineProperty({}, 'x', {})
(instead of using Array.prototype
) but that's a minor quibble; your example tests exact functionality (and so has less chance of false positives).
这篇关于解决IE8破坏的Object.defineProperty实现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!