prototypical inheritance javascript

83 Views Asked by At

Coming from a Java background, Javascript is a new world I'm trying to grasp.
Im kind of struggeling with how prototypical inheritance exactly works.
What i got from __proto__ VS. prototype in JavaScript and other sources was helpfull but I really want to make sure I grasp this topic. Are the following statements right?

__proto__, a property of objects, is an object which represents the prototype of the object. This object can in turn also have an __proto__ property until the Object object, the end of the chain is reached.

prototypeis a property on a function object and is an object itself. When an object is instantiated from a function using the new keyword, the __proto__ of that new instance will be the prototype property of the constructor function. For instance:

let random =  new Array();

console.log(random.__proto__);   //logs the object which is the prototype of random
console.log(Array.prototype);    //logs the same object as random.__proto__

console.log(random.__proto__.__proto__);  // logs the Object prototype object
console.log(Object.prototype);        // logs the same object as random.__proto__.__proto__

Also when the objects are tested with each other for equality they are the same object in the following code:

console.log(random.__proto__ === Array.prototype);               // logs true
console.log(random.__proto__.__proto__ === Object.prototype );   // logs true

Since objects are tested for equality by reference does this mean that there is actually one instance of the Object.prototype object and that all objects __proto__refer to this instance?

Thanks in advance.

1

There are 1 best solutions below

0
On BEST ANSWER

If you console.log(typeof(Ojbect)) and console.log(typeof(Array)) you got a "function" All that isn't a primitive type (undefined, null ...) is an object or "an instance" in JavaScript, means functions inherits from object.