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.

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❀ or a friendly comment on this post if you found it helpful!

Okay