Blog

Object

JS

prototype vs __proto__

Protoype inherientence & __proto__

Ragav Kumar V

Ragav Kumar V

Aug 20, 2022 ยท 2 min read

  1. __proto__ refers to the object's friend
  2. kayathri is friend of satya due to setPrototypeOf

_10
var satya = { eraser: "apsara" };
_10
var kayathri = { pencil: "camlin", sharper: "natraj" };
_10
_10
Object.setPrototypeOf(satya, kayathri);
_10
_10
console.log(satya.pencil);
_10
// "camlin"
_10
_10
console.log(kayathri.eraser);
_10
// undefined

satya.__proto__ (friend) points to kayathri. Moreover, satya can use all keys of kayathri. But, kayathri cannot use keys of satya

An object can have only one friend

  1. satya.__proto__ (friend) points to kayathri
  2. satya can use all keys of kayathri
  3. But kayathri cannot use keys of satya
  4. An object can have only one friend
  5. Object.prototype is common friend of all object

_16
var satya = { eraser: "apsara" };
_16
var kayathri = { pencil: "camlin", sharper: "natraj" };
_16
var badri = { books: ["eng", "tamil", "sci"] };
_16
_16
Object.setPrototypeOf(satya, kayathri); // satya is friend of kayathri
_16
Object.setPrototypeOf(kayathri, badri); // kayathri is friend of badri
_16
_16
// satya -> kayathri -> badri
_16
_16
console.log(satya.__proto__ === kayathri); // true
_16
console.log(kayathri.__proto__ === badri); // true
_16
_16
console.log(kayathri.books);
_16
// ["eng", "tamil", "sci"]
_16
console.log(satya.books);
_16
// ["eng", "tamil", "sci"]


_12
function Account(name, accno, balance) {
_12
this.name = name;
_12
this.accno = accno;
_12
this.balance = balance;
_12
this.getBalance = function () {
_12
return `The balance is: โ‚น${this.balance}`;
_12
};
_12
}
_12
_12
const ragu = new Account("Ragu", 1000, 1_00_000);
_12
const mohamed = new Account("Mohamed", 1001, 37_00_000);
_12
console.log(ragu.getBalance === mohamed.getBalance); // false


_14
function Account(name, accno, balance) {
_14
this.name = name;
_14
this.accno = accno;
_14
this.balance = balance;
_14
}
_14
_14
// Joint family | common friend
_14
Account.prototype.getBalance = function () {
_14
return `The balance is: โ‚น${this.balance}`;
_14
};
_14
_14
const ragu = new Account("Ragu", 1000, 1_00_000);
_14
const mohamed = new Account("Mohamed", 1001, 37_00_000);
_14
console.log(ragu.getBalance === mohamed.getBalance); // true

@ragavkumarv
swipe to next โžก๏ธ