0

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.

JMP
  • 4,417
  • 17
  • 30
  • 41
  • Primitives don't inherit a prototype. With your own prototypes you can add inheritable custom methods to your objects. Though possible, but strongly not recommended, the native prototypes are customizable too (modifying native prototypes is called "monkey patching"). – Teemu Mar 17 '23 at 07:49
  • still it is not explain how ```a.sayHi()``` works for variable ```a``` when we add ```sayHi()``` in ```obj``` prototype. please elaborate on that. – Jaikaran saini Mar 17 '23 at 08:32
  • https://stackoverflow.com/questions/53149349/how-does-primitive-types-in-javascript-have-methods-and-properties – Teemu Mar 17 '23 at 08:33
  • "*Does they really share same prototype?*" - see [`Object.prototype`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#object_prototype_properties). "*What is need of prototype chaining when all objects share same prototype?*" - not sure I understand the question? Are you asking why functions and numbers have a different prototype? – Bergi Mar 17 '23 at 09:07

0 Answers0