如何在JavaScript中为IE8添加非可枚举属性? [英] How to add non-enumerable property in JavaScript for IE8?
问题描述
有没有办法将隐藏的不可枚举属性添加到跨浏览器的JavaScript对象?
Is there a way to add "hidden" non-enumerable properties to a JavaScript object that works cross-browser?
对于大多数现代浏览器,您可以执行以下操作:
For most modern browsers, you can do:
Object.defineProperty(obj, '__id__', { enumerable: false, value: id++ });
对于一些没有 Object.defineProperty的旧版非IE浏览器
,你可以使用 __ proto __
hack 。
For some older non-IE browsers that don't have Object.defineProperty
, you can use the __proto__
hack.
然而,这些都不适用于IE 。有没有办法在IE8中实现这一点(如果IE7也会很酷,但不是必需的)?
None of those, however, work for IE. Is there a way to accomplish this in IE8 (would be cool if IE7 too, but not necessary)?
主要目标是能够向任何人添加跟踪器属性JavaScript {}
对象,但是当你调用 JSON.stringify(obj)
时,它不会包括在内在酒店。我意识到你可以添加自定义JSON替换器函数(基本上扩展 JSON.stringify
功能),但我不是那么忠实,因为它意味着你有时候序列化这些将JavaScript对象跟踪为JSON,您必须知道/记得添加替换函数这是非常不切实际的。
The main goal is to be able to add tracker properties to any JavaScript {}
object, but such that when you call JSON.stringify(obj)
, it doesn't get included in the property. I realize you can add custom JSON replacer functions (basically extending the JSON.stringify
functionality), but I'm not a big fan of that because it means any time you serialized these tracked JavaScript Objects into JSON, you would have to know/remember to add that replacer function which is pretty impractical.
有没有办法实现这个目标?
Is there any way to accomplish this?
推荐答案
我无法在IE10中的IE8兼容模式下重现它,但是
定义了像toLocaleString这样的属性
应该有效,因为 IE8中没有枚举错误。
Well I cannot reproduce it in IE8 compatability mode in IE10 but
defining a property like "toLocaleString"
should work because of the don't enum bug in IE8.
var uniqueId = function() {
var dontEnumBug = false;
var id = 0;
if( !Object.defineProperty ) {
var keyVisited = false;
for( var k in {toLocaleString: 3}) {
if( k === "toLocaleString" ) {
keyVisited = true;
}
}
if( !keyVisited ) {
dontEnumBug = true;
}
}
return function( obj ) {
if( dontEnumBug ) {
obj.toLocaleString = id++;
}
else {
Object.defineProperty(obj, '__id__', { enumerable: false, value: id++ });
}
}
})();
您还可以使用isPrototypeOf
或propertyIsEnumerable
因为这些函数几乎从未被调用过。
You could also use "isPrototypeOf"
or "propertyIsEnumerable"
as these are also functions that are pretty much never called.
这篇关于如何在JavaScript中为IE8添加非可枚举属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!