Prototype in JavaScript

Prototype in JavaScript

This is one of my short notes while I was studying about the prototype in Js. If you have time you can read.

So what is prototype?

In JavaScript, a prototype is a mechanism that allows objects to inherit properties and methods from other objects.

See this example of prototype inheritance in JavaScript:

const grandP = {
  name: "Rahim Uddin",
  age: 89,
  occupation: "farmer",
  isAlive: "YES"
}

const parent = {
  __proto__: grandP,
  name: "Karim Uddin",
  age: 50,
  occupation: "Teacher"
}

const child = {
  __proto__: parent,
  name: "Shahab",
  age: 20
}

console.log(child.occupation); // returns "Teacher"
console.log(child.isAlive); // returns "YES"        

As you can see I console.log(child.occupation). But occupation is not present in child object.

JavaScript will not stop here. It goes parent object that declared with '__proto__' It check there and it find occupation on parent and print "Teacher". Same goes console.log(child.isAlive).

Object "child -> parent -> grandP" , it is call prototype chain. And that's how this is works in JavaScript.

JavaScript first checks whether they exist on that object directly, and if not, it looks in [[Prototype]]. [[Prototype]] is looked at recursively, i.e. a1.doSomething, Object.getPrototypeOf(a1).doSomething, Object.getPrototypeOf(Object.getPrototypeOf(a1)).doSomething etc., until it's found or Object.getPrototypeOf returns null. This means that all properties defined on prototype are effectively shared by all instances, and you can even later change parts of prototype and have the changes appear in all existing instances.

If, you do const a1 = new A(); const a2 = new A();, then 'a1.doSomething' would actually refer to 'Object.getPrototypeOf(a1).doSomething' — which is the same as the 'A.prototype.doSomething' you defined, i.e. 'Object.getPrototypeOf(a1).doSomething' === 'Object.getPrototypeOf(a2).doSomething' === 'A.prototype.doSomething'

It is essential to understand the prototypal inheritance model before writing complex code that makes use of it. Also, be aware of the length of the prototype chains in your code and break them up if necessary to avoid possible performance problems. Further, the native prototypes should never be extended unless it is for the sake of compatibility with newer JavaScript features.

To view or add a comment, sign in

Explore content categories