I am learning about prototypes in Javascript, and while practicing it I found that when I add some method to prototype of an object, then the same function is also callable with any other variables or functions. I previously knew that functions and objects also had prototypes but I did not know they share the same prototypes by default. Can anyone elaborate on that? Does they really share same prototype? if yes then, What is need of prototype chaining when all objects share same prototype?
let a = 10;
const fun = function () {
return 'i am fun';
}
const obj = {
greet: 'hi there!'
}
obj.__proto__.sayHi = function () {
return this.valueOf();
}
console.log(obj.sayHi()); // { greet: 'hi there!' }
console.log(a.sayHi()); // 10
console.log(obj.__proto__ === a.__proto__.__proto__ && obj.__proto__ === fun.__proto__.__proto__); // true
console.log( a.__proto__.__proto__); // [Object: null prototype] { sayHi: [Function (anonymous)] }
As of this code I think this is prototypes are chained.
//
// |--------> null
// ____|___
// |------> \ proto \ <----------------------|
// | \sayHi()\ <-------| |
// | \_______\ | |
// ______ | ___|____ ____|____
// / obj /-----| |-----> \ proto \ \ proto \ <-------|
// /_____/ | \_______\ \________\ |
// | |
// | _______ _______ |
// |-----/ a / / fun /-----|
// /______/ /______/
//
please correct me if I am conceptually wrong.