Search⌘ K
AI Features

Implementing Inheritance

Explore JavaScript inheritance by understanding prototypes, the prototype chain, and how the new keyword connects them. Learn why placing methods on function prototypes improves performance and memory efficiency compared to attaching methods directly to objects. Gain insights into the constructor property, __proto__ relationships, and using Object.create for manual inheritance setup.

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:

Javascript (babel-node)
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
...