DEV Community

Dan-Vy Le
Dan-Vy Le

Posted on • Edited on

JavaScript Fundamentals 101: Prototypal Inheritance

Prototypal inheritance is a unique feature in JavaScript. Each object in JavaScript has a private property which holds a link to another object called its prototype. So in a sense, if it is not stated that your dad has brown eyes(Assuming a dominant trait is brown eyes), we can infer that he has brown eyes if your grandpa has documented that he has brown eyes by prototypal inheritance.

To set and get prototypes of objects, it would look like so:

Object.getPrototypeOf()

Object.setPrototypeOf()

__proto__

//For the sake of simplicity, we'll use __proto__ to set and get our prototypes

Let's use the example of your grandpa, your dad and you. Grandpa's family name is Nguyen:

let nguyen = {
  brownEyes: true,
  speaksVietnamese() {
    console.log("Chao ban!")
  }

};
let daddy = {
  blackHair: true
};

daddy.__proto__ = nguyen;

// Daddy has a few properties now, one by declaration, one by inheritance and he can inherit functions from grandpa too:
console.log(daddy.brownEyes); // true (**)
console.log(daddy.blackHair); // true
daddy.speaksVietnamese(); // "Chao ban!"

This chain of inheritance can continue to extend, as long as it doesn't loop. Let's add ourselves into the mix:

let myself = {
  nextGeneration: 2.0,
  __proto__: daddy
};

console.log(myself.brownEyes); // true (**)
console.log(myself.blackHair); // true
myself.speaksVietnamese(); // "Chao ban!"

ECMAScript 2015 introduced a new set of keywords implementing classes. The new keywords include class, constructor, static, extends, and super. We can get into this on a later blog!

I hope that helps simplify prototypal inheritance for you! Please let me know if you have any questions or comments!

sources included:

https://javascript.info/prototype-inheritance

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

Top comments (0)