Scipion
Scipion

Reputation: 1380

Why Object.prototype.__proto__ === null

In JavaScript non-standard property __ proto__ and function Object.getPrototypeOf (...) return the internal property [[Prototype]].

For all functions the property 'prototype' is an instance of Object.prototype, for example:

Array.prototype instanceof Object//true

But not so with Object.prototype:

Object.prototype.__proto__ === null //true
Object.getPrototypeOf( Object.prototype ) === null //true

mozilla developer documentation only says:

An Object's proto property references the same object as its internal [[Prototype]] (often referred to as "the prototype"), which may be an object or, as in the default case of Object.prototype.proto, null .

Would it be more appropiate that Object.prototype.proto or failing Object.getPrototypeOf (Object.prototype) return Object.prototype?

Is this a bug? Is this ok? why?

Upvotes: 1

Views: 1469

Answers (2)

nebula
nebula

Reputation: 11

While Object.prototype.__proto__ is supported today in most browsers, its existence and exact behavior has only been standardized in the ECMAScript 2015 specification as a legacy feature to ensure compatibility for web browsers. For better support, use Object.getPrototypeOf() instead.

link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto

Upvotes: 1

SLaks
SLaks

Reputation: 887459

The prototype chain has to stop somewhere.

Had Object.getPrototypeOf( Object.prototype ) === Object.prototype, the JS engine would get into an infinite loop when it tries to resolve something from the prototype.

It would walk up the prototype chain to Object.prototype, and, if it doesn't find it there, it would walk further up to Object.prototype again, ad infinitum.

In fact, if you try to do that yourself, you'll get an error:

> Object.prototype.__proto__ = Object.prototype
Error: Cyclic __proto__ value

Note that you can also create your own objects with no [[Prototype]] by calling Object.create(null).

Upvotes: 5

Related Questions