Reputation: 135
Why is it possible to change Object.prototype.proto from null.
Object.prototype is one of the rare objects that has no prototype, and it is not inheriting any properties (according to Flanagan)
I cant imagine how to use Object.prototype.proto in real life. Please give me an example why is it necessary to change it
Upvotes: 1
Views: 124
Reputation: 664579
Why is it possible to change
Object.prototype.__proto__
fromnull
?
Well, it is not possible. Try it yourself in any modern browser:
> Object.setPrototypeOf(Object.prototype, Object.create(null))
Uncaught TypeError: Immutable prototype object '#<Object>' cannot have their prototype set
These immutable prototype exotic objects were introduced with ES7.
Upvotes: 1
Reputation: 120
Here is a whole page about Object.prototype.proto link note that it is used as a getter and setter method to expose the prototype of an object and that it has been deprecated in favor Object.getPrototypeOf and Object.setPrototypeOf. It has plenty of uses when you want to change the properties of an Objects prototype.
Upvotes: 1
Reputation: 1074475
I cant imagine how to use
Object.prototype.__proto__
in real life
You wouldn't use it on Object.prototype
itself. __proto__
is an accessor property inherited by all objects that inherit from Object.prototype
. You can use it to get, or even change, their prototype (but shouldn't, keep reading). E.g.:
class X {
}
let o = {};
console.log(o.__proto__ === Object.prototype); // true
o.__proto__ = X.prototype;
console.log(o instanceof X); // true
console.log(o.__proto__ === Object.prototype); // false
It's provided primarily to offer compatibility with existing code on the web that used a proprietary extension to JavaScript in Mozilla's JavaScript engines. Instead of using o.__proto__
, use Object.getPrototypeOf(o)
and Object.setPrototypeOf(o, ...)
. (In fact, officially JavaScript engines aren't supposed to have __proto__
at all except when they're being used in web browsers. It's defined in an annex to the spec, not the spec itself, which only applies to web browser JavaScript engines.)
An in general, don't even use Object.setPrototypeOf
. Changing the prototype of an object after it's been constructed is almost always indicative of a design problem. (And makes subsequent operations on the object very slow [in relative terms].)
Upvotes: 2