Search code examples
javascriptobjectprototype

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. if arguments[0] is {a: 'a', b: 'b'}, it iterates through a,b,forEach. How can I solve this?

Thank you in advance.


Solution

  • It's a very bad idea ever to add to 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 [e.g., for getting iterators and similar].)

    But if you do it anyway, ensure that the property you add is non-enumerable by using 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.