Search code examples
javascriptprototypehasownproperty

Is there any way to recover from somebody changing Object.prototype.hasOwnProperty?


You always read that for-in loops should check o.hasOwnProperty(k) to skip over Object.prototype. Well, if somebody is stupid enough to modify Object.prototype, who's to say they won't do anything that conflicts with the existing prototype? For example, what if somebody runs this:

Object.prototype.hasOwnProperty = function () {
    return !!'I am stupid';
};

If this is the first script run, does this mean that, for every script on the rest of the page, it is actually impossible to safely iterate over an object?


Solution

  • You can create a temporary IFRAME element, and retrieve the method from its Object.prototype object:

    (function () {
        var frame = document.createElement( 'iframe' );
        frame.style.display = 'none';
        document.body.appendChild( frame );
        Object.prototype.hasOwnProperty = frame.contentWindow.Object.prototype.hasOwnProperty;
        document.body.removeChild( frame );
    }());
    

    Live demo: http://jsfiddle.net/ARycC/2/