Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you make an object in Javascript which does NOT inherit from Object?

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...)

like image 348
Vilx- Avatar asked Jan 25 '12 15:01

Vilx-


People also ask

Can objects inherit from other objects in JavaScript?

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.

Which inheritance Cannot be implemented in JavaScript?

Excerpt from JavaScript advanced programming The method has no signature, and interface inheritance cannot be implemented in ECMAScript.

Does function inherit from object in JavaScript?

prototype is last in the prototype chain and it doesn't inherit from anything. The Object constructor is the one that inherits from Function.

Is inheritance possible in JavaScript If yes what type is possible?

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.


2 Answers

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

> obj = Object.create(null);
  Object
    No Properties
like image 168
Felix Kling Avatar answered Sep 24 '22 01:09

Felix Kling


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];
like image 26
kennebec Avatar answered Sep 23 '22 01:09

kennebec