DEV Community

 Bishnu Prasad Chowdhury
Bishnu Prasad Chowdhury

Posted on • Edited on

Javascript prototype and prototypal inheritance

When an object/array/ function is created, the javascript engine adds access to hidden properties and method under _ _ proto _ _ object.

function b (){
   console.log("function");
};
let a = {
  id : 1,
  name : "jack",
  showScore: function (){
      console.log(this.id + " :" + this.name);
    }
}
a._ _ proto _ _
Object.prototype

a._ _ proto _ _ . _ _ proto _ _
null

b. _ _ proto _ _
Function.prototype

b. _ _ proto _ _ . _ _ proto _ _
Object.prototype

b. _ _ proto _ _ . _ _ proto _ _ . _ _ proto _ _
null
Enter fullscreen mode Exit fullscreen mode

Hence we can say everything in javascript is an object.

let a = {
  name: "mavy",
  age: 16,
  place: "AU"
  showName: function (){
     console.log(this.name);
   };
};

let b = {
  name: "redis"
};


b. _ _ proto _ _ = a
// Avoid such code

b.name
"redis"

b.age
16

b.showName()
"redis"

Enter fullscreen mode Exit fullscreen mode

Here b is inheriting from a using prototyping inheritance.

We can implement new logic to existing methods of prototype and everytime it will be called it will load that function.

Function.prototype.test =  function (){ console.log(true); }

function a() {};

a.test()
true
Enter fullscreen mode Exit fullscreen mode

Like this, all functions can now have access to the function through prototype.test property.

Top comments (0)