tags:

views:

171

answers:

2

Hi everyone,

I have a web page that when I try to create a JavaScript object in it using:

var myVar = {};

The resulting object always contains an inherit property, this interferes with my code and doesn't happen except on this page only, anyone knows why?

+4  A: 

Somebody done gone and put somethin on Object.prototype. Check it yourself:

for(var k in {}) alert(k); // should get NO alerts

As for tracking it down, use the output of above to search your codebase. First places to check are any external libraries you are including in <script src="..."></script> tags. For example really old versions of the Prototype library augmented Object.prototype.

Update re comment from @Ahmad:

You have two choices:

  1. Move the implementation off the prototype to instead take the thing to extend as the first parameter, eg:

    Object.inherit = function(obj, superClass, superClassName) {
      /* change "this" to "obj" all throughout the code here */
    }
    

    And refactor all places that do:

    foo.inherit(a, b)
    

    to instead do:

    Object.inherit(foo, a, b)
    

    This approach may require a large re-factoring effort obviously. The benefit is you leave Object.prototype alone.

  2. The 2nd approach is to leave the code that does Object.prototype.inherit = ... alone, and instead refactor the code you are trying to write right now to use hasOwnProperty, which will tell you if a property has been set directly on your object (i.e. without trudging through the object's prototype chain):

    for(var k in myVar) {
      if (myVar.hasOwnProperty(k)) {
        /* ... */
      }
    }
    

    And of course be judicious in the use of hasOwnProperty in all future for..in code that enters the codebase.

You can do both to clean up your codebase and be future-proof against other libraries that enter the code that alter Object.prototype themselves.

Crescent Fresh
@Ahmad: so was there a library at fault? Curious....
Crescent Fresh
It is not a library fault, there is a js file that adds the inherit function to the Object prototype like this:Object.prototype.inherit = function(superClass, superClassName){...};You know how to fix this without removing the above? because it is needed in other parts of the page
Ahmad
@Ahmad: see my update
Crescent Fresh
A: 

Perhaps some script you are including are modifying the Object.prototype to add its own custom functions.

John Riche