Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Javascript, why is there no "prototype" property for an instance or object literal?

In Javascript, any "function object" has a prototype

> F = function() {}
F()
> F.prototype
F {}

But "object" or "instance" doesn't have a prototype

> o = {}
Object {}
> o.prototype
undefined
> f = new F()
F {}
> f.prototype
undefined

However, the built-in object "Function" and "Object" have a prototype:

> Function.prototype
Empty()
> Object.prototype
Object {}

This looks quite confusing for me.

  1. Function and "function object" have a prototype property

  2. Object has a prototype property, but "object literal" and "instance object" doesn't have a prototype property

What does the prototype property actually mean? In the example above, shouldn't the prototype property of f be F?

Does anyone have ideas about how to explain this? Thanks!

like image 728
Hanfei Sun Avatar asked Jun 30 '15 07:06

Hanfei Sun


People also ask

Do all JavaScript objects have a prototype property?

Each and every JavaScript function will have a prototype property which is of the object type. You can define your own properties under prototype . When you will use the function as a constructor function, all the instances of it will inherit properties from the prototype object.

Which object in JavaScript does not have a prototype?

Both objectOne and objectTwo are non-function objects therefore they don't have a prototype property.

Do all functions have a prototype property?

Note: Not all Function objects have the prototype property — see description.

What is prototype property in JavaScript?

Every object in JavaScript has a built-in property, which is called its prototype. The prototype is itself an object, so the prototype will have its own prototype, making what's called a prototype chain. The chain ends when we reach a prototype that has null for its own prototype.


1 Answers

Don't confuse the prototype attribute of a function with the internal prototype of an object (which places the object in the prototype chain).

Function and Object are constructor functions, as such, they have a prototype attribute, which will be assigned as the internal prototype of objects created with these constructor functions.

I recommend Eloquent Javascript's chapter "The secret life of objects", particularly for this quote:

It is important to note the distinction between the way a prototype is associated with a constructor (through its prototype property) and the way objects have a prototype (which can be retrieved with Object.getPrototypeOf). The actual prototype of a constructor is Function.prototype since constructors are functions. Its prototype property will be the prototype of instances created through it but is not its own prototype.

like image 71
doldt Avatar answered Nov 14 '22 23:11

doldt