Inheritance in Javascript

Hi, in this post I’m going to explain the inheritance in Javascript.

In Javascript all the objects have an internal property called [[prototyped]] that points to another object called “prototyped“.

The prototyped object has a prototype object of its own and so on until a final prototype object have null as its prototype object.

And because null has not prototype object then it acts as final of the prototype chain.

For example:

So, every time that we search for a property in the object and the property is not found in that object then the chain prototype is executed, looking that property into the prototype objects until null appears in the chain and this is called inheritance.

Remember that is only 1 prototype object by object, this means that is a single inheritance.

The __proto__ property of the object literal

// Object literal declaration called myObject
let obj = {
  name: "Cristina Rojas",
};

console.log('obj.__proto__ --->', obj.__proto__)

Result:

The __proto__ and Object.setPrototypeOf() can be used to assign a prototype of an object.

// Object literal declaration called myObject
let obj = {
  name: "Cristina Rojas",
  __proto__: {
    age: 32
  }
};

console.log('obj.__proto__ --->', obj.__proto__)

Result: the prototype object of obj is { age: 32 }

Object.setPrototypeOf():

// Object literal declaration called myObject
let obj = {
  name: "Cristina Rojas",
};

Object.setPrototypeOf(obj, { age: 32 });

console.log("obj.__proto__ --->", obj.__proto__);

Result:

In both cases the object { age: 32 } is known as base object, superobject or parent object.

And in both cases the object { name: “Cristina Rojas” } is known as derived object, subobject or child object.

Note:

If we don’t assign a prototype to an object while we are creating the object, then the prototype of that object will point to the Object.prototype property and remember that the prototype of Object.prototype is null and null means the end of the chain.

By Cristina Rojas.