Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript inheritance : How prototype chain works between native prototypes

As we know everything in Javascript inherits from Object:

Inheritance

So if I create an object using constructor function like below:

function Rabbit() {
  this.color = 'White'
}

let obj = new Rabbit();

alert(Rabbit.__proto__ === Function.prototype)       //true
alert(obj.__proto__ === Rabbit.prototype)            //true       
alert(obj.__proto__.__proto__ === Object.prototype)  //true

alert(Function.__proto__ === Object.prototype)  //false
alert(Object.getPrototypeOf(Function) === Object.getPrototypeOf(Object))  //true

The first 3 results make sense because obj inherits from Rabbit function which itself inherits from Function. But if Function inherits from Object then why is the 4th result False. Also why do both Object and Function have same prototype (last result)?

Can someone explain this behavior. Am i missing something here?

like image 983
D_S_X Avatar asked Sep 06 '25 05:09

D_S_X


2 Answers

Problems like this are better explained with images (like the one in your question):

enter image description here

Legend:

   blue color = objects
   {} = simple object (+constructor name)
   Ⓟ = prototype object (+constructor name)

   magenta color = functions (ƒ + function name)

Basically, the __proto__ chain for functions is:

concrete function (e.g. Rabbit, Object or Function itself) 
-> abstract function (aka Function.prototype) 
-> Object.prototype 
-> null 
like image 193
georg Avatar answered Sep 09 '25 02:09

georg


alert(Object.getPrototypeOf(Function) === Object.getPrototypeOf(Object)) // true

Both Function and Object are functions, their prototype is Function.prototype. Can be verified with

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

This very object was used to create the prototype of Function function, thus

Function.__proto__ === Function.prototype // true

rather than

Function.__proto__ === Object.prototype // false

alert(Object.getPrototypeOf(Function) === Function.prototype)
alert(Object.getPrototypeOf(Object) === Function.prototype)
alert(Function.__proto__ === Function.prototype)
like image 30
Wiktor Zychla Avatar answered Sep 09 '25 02:09

Wiktor Zychla