简体   繁体   English

当扩展Obect.prototype然后在等距上使用for时,js也会遍历原型

[英]When extending Obect.prototype and then using for in on a istance, js iterate through prototype too

I add this method to the object prototype: 我将此方法添加到对象原型中:

if( !Object.prototype.forEach ) {
    Object.prototype.add({
       'forEach': function(fn) {
            var object = this, ret;

            Object.keys(object).forEach(function(key) {
                if (ret === false)
                    return;

                ret = fn.call(null, object[key], key, object);
            });

            return object;
        }
    });
}

then do this: 然后这样做:

 switch( typeOf( arguments[0] ) ) {
     case 'string':
         // ...

     case 'object':
         var prop;
         for(prop in arguments[0]) {
             // ...
         }

And the code iterates through forEach too. 并且代码也通过forEach迭代。 if arguments[0] is {a: 'a', b: 'b'} , it iterates through a,b,forEach . 如果arguments[0]{a: 'a', b: 'b'} ,则迭代a,b,forEach How can I solve this? 我该如何解决?

Thank you in advance. 先感谢您。

It's a very bad idea ever to add to Object.prototype . 添加到Object.prototype是一个非常糟糕的主意。 The opportunity for conflicts is just too great. 冲突的机会太大了。 You could use a lib that happens to use the property name you added as a marker, doing one thing if it's present on a given object but something else if it isn't. 您可以使用一个碰巧使用添加为标记的属性名的库,如果给定对象中存在该属性名,则做一件事,如果不存在,则做其他事情。 (ES2015 actually had to add a whole new kind of property name [ Symbol ] in order for built-in operations to have logic like that [eg, for getting iterators and similar].) (ES2015实际上必须添加一种全新的属性名称[ Symbol ],以便内置操作具有类似的逻辑(例如,用于获得迭代器等)。)

But if you do it anyway, ensure that the property you add is non-enumerable by using Object.defineProperty : 但是,无论如何,请使用Object.defineProperty确保添加的属性不可枚举

Object.defineProperty(Object.prototype, "forEach", {
    value: function() { /*...*/ },
    enumerable: false // This is actually the default, just here for emphasis
});

I'd suggest that wherever you got that Object.prototype.add function is probably not a place to learn from. 我建议无论您在哪里获得Object.prototype.add函数,都可能不是一个Object.prototype.add学习的地方。

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

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