【題記】每次看《javascript高級程序設計》第九章第二節的“怪癖檢測”的時候,看到IE的bug,看一下,知道有這么一個東西,因為實際項目中還沒有用到這個,今天再看,勢必要把這個搞清楚。
【正文】如果某個實例屬性與標為[[DontEnum]]的某個屬性同名,那么該實例屬性不會出現在for in,
測試
<
div
id
="txt"
></
div
>
< script >
var arr = {
" first " : 1 ,
" second " : 2 ,
" third " : 3 ,
toString : function (){},
valueOf : function (){},
constructor : 11 ,
hasOwnProperty : function (){},
isPrototypeOf : function (){}
/* propertyIsEnumerable : function(obj){
} */
};
var txt = document.getElementById( " txt " );
var str = "" ;
for ( var o in arr){
str += o + " 's [[DontEnum]] is " + arr.propertyIsEnumerable(o) + " <br /> " ;
}
txt.innerHTML = str;
</ script >
< script >
var arr = {
" first " : 1 ,
" second " : 2 ,
" third " : 3 ,
toString : function (){},
valueOf : function (){},
constructor : 11 ,
hasOwnProperty : function (){},
isPrototypeOf : function (){}
/* propertyIsEnumerable : function(obj){
} */
};
var txt = document.getElementById( " txt " );
var str = "" ;
for ( var o in arr){
str += o + " 's [[DontEnum]] is " + arr.propertyIsEnumerable(o) + " <br /> " ;
}
txt.innerHTML = str;
</ script >
結果如下,IE9,firefox,chrome,safari,opera都顯示如下:
而IE8,6,7顯示如下:
可見,IE9已經修復了這個bug, IE8以及版本以下的bug依然存在,同時,被打上[[DontEnum]]的屬性有:toString,valueOf,constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable
最后,檢測這個bug就更簡單了,
var isDontEnum = (
function(){
for ( var p in { toString: 1 }) {
if (p === 'toString') return false;
}
return true;
})();
for ( var p in { toString: 1 }) {
if (p === 'toString') return false;
}
return true;
})();
那么,如何修復這個BUG呢?
1
/*
@cc_on if(o.toString!=={}.toString){
2 // doStuff ... for example
3 alert(o.toString);
4 }@ */
2 // doStuff ... for example
3 alert(o.toString);
4 }@ */
Dean Edwards
1
/*
@cc_on
2 if(o.toString!==Object.prototype.toString){
3 // doStuff
4 }
5 if(o.valueOf!==Object.prototype.valueOf){
6 // doStuff
7 }
8 @ */
2 if(o.toString!==Object.prototype.toString){
3 // doStuff
4 }
5 if(o.valueOf!==Object.prototype.valueOf){
6 // doStuff
7 }
8 @ */
參考:
http://webreflection.blogspot.com/2007/07/quick-fix-internet-explorer-and.html