简体   繁体   English

如何在IE8的JavaScript中添加不可枚举的属性?

[英]How to add non-enumerable property in JavaScript for IE8?

Is there a way to add "hidden" non-enumerable properties to a JavaScript object that works cross-browser? 有没有办法向跨浏览器工作的JavaScript对象添加“隐藏的”不可枚举的属性?

For most modern browsers, you can do: 对于大多数现代浏览器,您可以执行以下操作:

Object.defineProperty(obj, '__id__', { enumerable: false, value: id++ });

For some older non-IE browsers that don't have Object.defineProperty , you can use the __proto__ hack . 对于某些没有Object.defineProperty较旧的非IE浏览器,可以使用__proto__ hack

None of those, however, work for IE. 但是,这些都不适用于IE。 Is there a way to accomplish this in IE8 (would be cool if IE7 too, but not necessary)? 有没有办法在IE8中完成此操作(如果也使用IE7,那会很酷,但这不是必需的)?

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. 主要目标是能够将跟踪器属性添加到任何JavaScript {}对象,但是这样,当您调用JSON.stringify(obj) ,它就不会包含在该属性中。 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. 我意识到您可以添加自定义JSON JSON.stringify功能(基本上扩展了JSON.stringify功能),但是我并不那么喜欢它,因为这意味着您JSON.stringify将这些跟踪的JavaScript对象序列化为JSON时,都必须知道/记住添加那个非常不切实际的替换功能。

Is there any way to accomplish this? 有什么办法可以做到这一点?

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 . 好吧,我无法在IE10的IE8兼容模式下重现它,但由于IE8中没有枚举错误,因此定义"toLocaleString"类的属性应该可以工作。

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++ });
        }

    }

})();

You could also use "isPrototypeOf" or "propertyIsEnumerable" as these are also functions that are pretty much never called. 您还可以使用"isPrototypeOf""propertyIsEnumerable"因为这些也是几乎从未调用过的函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM