Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
271 views
in Technique[技术] by (71.8m points)

javascript - Working around IE8's broken Object.defineProperty implementation

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();

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...