for-in JavaScript语句中的IE8错误? [英] IE8 bug in for-in JavaScript statement?
问题描述
我想我已经在IE(IE8)处理for-in javascript语句中发现了一个错误。经过几个小时的煮沸,这是一个小例子,看起来IE特意在for-in循环中跳过任何名为toString的属性 - 无论它是在原型中还是对象的自有属性。
I think I've found a bug in IE's (IE8) handling for the for-in javascript statement. After several hours of boiling this down to a small example, it looks like IE specifically skips any property called "toString" in a for-in loop - regardless of whether it is in a prototype or is an "Own Property" of the object.
我已将测试代码:
function countProps(obj) {
var c = 0;
for (var prop in obj) {
c++;
}
return c;
}
var obj = {
toString: function() {
return "hello";
}
};
function test() {
var o = "";
var d = document.getElementById('output');
o += "<br/>obj.hasOwnProperty('toString') == " + obj.hasOwnProperty('toString');
o += "<br/>countProps(obj) = " + countProps(obj);
o += "<br/>obj.toString() = " + obj.toString();
d.innerHTML = o;
}
这应该产生:
obj.hasOwnProperty('toString') == true
countProps(obj) = 1
obj.toString() = hello
但在IE中,我得到:
obj.hasOwnProperty('toString') == true
countProps(obj) = 0
obj.toString() = hello
任何名为'toString'的属性的特殊外壳破坏了我的代码,试图将方法复制到Function.prototype中 - 我的自定义toString函数总是跳过。
This special casing of any property called 'toString' is wrecking havoc with my code that tries to copy methods into a Function.prototype - my custom toString function is always skipped.
有没有人知道解决方法?这是某种怪癖模式的行为 - 或只是一个BUG?
Does anyone know a work-around? Is this some sort of quirks-mode only behavior - or just a BUG?
推荐答案
是的,这是一个错误。请参阅此答案。
Yes, it is a bug. See this answer.
引用 CMS :
另一个众所周知的JScript错误是DontEnum Bug,如果其作用域链中的对象包含一个不可枚举的属性(具有{DontEnum}属性),如果该属性在其他对象上被遮蔽,它将保持为不可枚举,例如:
Another well known JScript bug is the "DontEnum Bug", if an object in its scope chain contains a property that is not enumerable (has the { DontEnum } attribute), if the property is shadowed on other object, it will stay as non-enumerable, for example:
var dontEnumBug = {toString:'foo'}.propertyIsEnumerable('toString');
在IE上评估为false,这会在使用时导致问题for-in语句,因为不会访问属性。
It will evaluate to false on IE, this causes problems when using the for-in statement, because the properties will not be visited.
这篇关于for-in JavaScript语句中的IE8错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!