daniel_mj
daniel_mj

Reputation: 3

What difference betwwen Object.getPrototypeOf(Object) and Object.prototype?

>Object.getPrototypeOf(Object)
[Function: Empty]

>Object.prototype
{}

why I got difference result? But if I use:

>Object.getPrototypeOf({})
{}

everything is fine. Is any point I missed about getPrototypeOf??

Upvotes: 0

Views: 450

Answers (3)

Michele Tibaldi
Michele Tibaldi

Reputation: 196

I know this is old, but i just went through this and i didn't find a full picture anywhere. Assuming you're creating a custom constructor function Foo, it's like this:

JS proto diagram

Watch that both Object.__proto__ and Function.__proto__ point to Function.prototype, because both Object and Function are functions, just like Foo.

Upvotes: 0

allez l'OM
allez l'OM

Reputation: 577

I had a similar question: why?

Object.getPrototypeOf(Object) === Function.prototype;    // true
Object.getPrototypeOf(Object) === Object.prototype;      // false

though:

Object.getPrototypeOf(Function) === Function.prototype); // true
Object.getPrototypeOf(Function) === Object.prototype);   // false

Object and Function behave the same wrt getPrototypeOf, though Object.prototype and Function.prototype are different. The internal [[prototype]] of Function === its property, but the internal [[prototype]] of Object is not its property.

Looks peculiar (I don't see any other similar situation).

Yes indeed, Object is a function, so is Array, etc., so is Function. All are 'function'. Shouldn't we say that "objects are first-class functions"? (instead of reverse? just joking)

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 817128

Object.prototype is the object from which all other objects inherit. It is at the root of the prototype chain for built-in objects. From the MDN documentation:

All objects in JavaScript are descended from Object; all objects inherit methods and properties from Object.prototype, although they may be overridden [...]

Object.getPrototypeOf is a convenience method to get the prototype of a specific object. From the MDN documentation:

The Object.getPrototypeOf() method returns the prototype (i.e. the internal [[Prototype]]) of the specified object.

Different types of objects can have different prototypes.

Examples:

> Object.getPrototypeOf(Object) === Function.prototype
true

Object is a function, hence its prototype is Function.prototype.

> Object.getPrototypeOf(/foo/) === RegExp.prototype
true

/foo/ creates a regular expression, hence its prototype is RegExp.prototype.

> Object.getPrototypeOf([]) === Array.prototype
true

[] creates an array, its prototype is Array.prototype.

> Object.getPrototypeOf({}) === Object.prototype
true

{} creates a simple object, its prototype is Object.prototype.

Upvotes: 4

Related Questions