简体   繁体   中英

JavaScript Object Contains inherit Property

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?

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 (ie 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.

可能包括的某些脚本正在修改Object.prototype以添加其自己的自定义函数。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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