Implementing Inheritance

We'll dive into the nuances of prototypal inheritance and the tools that the language gives us to bend it to our needs. We'll discuss how prototypes and object '__proto__' properties help us implement inheritance.

We'll cover the following...

Inheritance

We now get to another computer science topic: inheritance. Inheritance refers to an object’s ability to access methods and other properties from another object. Objects can inherit things from other objects. Inheritance in JavaScript works through prototypes and this form of inheritance is often called prototypal inheritance.

Function prototypes

As mentioned, functions all have a prototype property distinct from their __proto__ property. It’s an object. A function’s prototype's __proto__ property is equal to Object.prototype. In other words:

Press + to interact
function fn() {}
const protoOfPrototype = Object.getPrototypeOf(fn.prototype);
// protoOfPrototype === fn.prototype.__proto__
console.log(protoOfPrototype === Object.prototype);
// -> true

Function Prototypes and new

A function’s prototype property shows its usefulness in object oriented programming. You might remember from the lesson on new that using new does something to the object bound to this in the constructor function.

Sets the object’s internal prototypal-inheritance property, __proto__, to be the prototype property of the constructing function.

We can now understand this.

When we call a function with new, it sets the returned object’s __proto__ property equal to the function’s prototype property. This is the key to inheritance.

We’ve assembled a few points so far:

  • The __proto__ of an object created by calling a function with new is equal to the prototype of that function
  • The __proto__ of a
...