Occasionally there is a JS framework or library that thinks it's a really wise idea to add some net new features to the prototype of Object
or Array
. I can't find any more examples right now, but I do remember that I've had problems with that before. Of course, doing so breaks the good old for(...in...)
loop, because suddenly those properties are now enumerated too. To get around it you have to check every enumerated property with .hasOwnProperty()
before accessing. Which is cumbersome, when trying to write robust code.
So I got wondering - is there some way that I could make my own objects so, that they don't inherit from Object
? Initial playing around with .prototype
yielded no results. Perhaps there is some trick to it? Or will everything always inherit from Object
and there's nothing I can do about it?
Added: I guess I should have noted 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 the more the better, of course. (Yes, sadly, the corporate world still lives in IE-world...)
In JavaScript, an object can inherit properties of another object. The object from where the properties are inherited is called the prototype. In short, objects can inherit properties from other objects — the prototypes.
Excerpt from JavaScript advanced programming The method has no signature, and interface inheritance cannot be implemented in ECMAScript.
prototype is last in the prototype chain and it doesn't inherit from anything. The Object constructor is the one that inherits from Function.
When it comes to inheritance, JavaScript only has one construct: objects. Each object has a private property which holds a link to another object called its prototype. That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype.
In ECMAScript 5 you can pass null
to Object.create
:
> obj = Object.create(null);
Object
No Properties
You can explicitly remove any Object properties that are enumerable, but moderen browsers allow nonenumerable Object methods.
Should work in older browsers though.
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With