Working around IE8's broken Object.defineProperty implementation

后端 未结 5 1196
一向
一向 2020-12-05 03:14

Consider the following code, using ECMAScript5\'s Object.defineProperty feature:

var sayHi = function(){ alert(\'hi\'); };
var defineProperty =          


        
5条回答
  •  情深已故
    2020-12-05 03:17

    I had the same kind issue (i.e. the Object.defineProperty in IE 8 being DOM only and not a full implementation as the other browsers), but it was for a polyfill..

    Anyhoo, I ended using a 'feature' check to see if I was using IE, its not perfect, but it works on all the tests I could do:

    if (Object.defineProperty && !document.all && document.addEventListener) {
        Object.defineProperty(Array.prototype,'sayHi',{value:sayHi});
    } else {
        Array.prototype.sayHi = sayHi;
    }
    

    as IE <= 8 has no document.addEventListener, and document.all is a proprietary Microsoft extension to the W3C standard. These two checks are equivalent to checking if IE is version 8 or below.

提交回复
热议问题