Can you create an object in Javascript that does NOT inherit the object?

Sometimes there is a JS framework or library that considers it really a reasonable idea to add some clean new features to the Object or Array prototype. I cannot find more examples right now, but I remember that I had problems with this before. Of course, this breaks the good old for(...in...) loop, because now these properties are now listed. To get around this, you should check all of the listed properties with .hasOwnProperty() before accessing. Which is cumbersome when you are trying to write reliable code.

So I was wondering - is there a way so that I can create my own objects so that they do not inherit from Object ? The initial game with .prototype yielded no results. Perhaps there is some kind of trick? Or is everything always inherited from Object , and I can do nothing about it?

Added: I assume that I should have noticed that I want it for client scripts in browsers, and compatibility should include IE6, or at least IE7. Other browser version requirements are more lenient, though, all the better, of course. (Yes, unfortunately, the corporate world still lives in the IE world ...)

+7
source share
2 answers

In ECMAScript 5, you can pass null to Object.create :

 > obj = Object.create(null); Object No Properties 
+4
source

You can explicitly remove any object properties that are listed, but moderen browsers allow the immeasurable Object methods.

Should work in older browsers.

 function Myobject(props){ } var O=Object,OP=Object.prototype; for(var p in O)delete Myobject[p]; for(var p in OP)delete Myobject.prototype[p]; 
+1
source

All Articles