Prototypal inheritance

So far we have seen some inheritance in action — we have seen how prototype chains work, and how members are inherited going up a chain. But mostly this has involved built-in browser functions. How do we create an object in JavaScript that inherits from another object?

Getting started

First of all, make yourself a local copy of our oojs-class-inheritance-start.html file (see it running live also). Inside here you'll find the same Person() constructor example that we've been using all the way through the module, with a slight difference — we've defined only the properties inside the constructor:

function Person(first, last, age, gender, interests) {
  this.name = {
    first,
    last
  };
  this.age = age;
  this.gender = gender;
  this.interests = interests;
};

The methods are all defined on the constructor's prototype. For example:

Person.prototype.greeting = function() {
  alert('Hi! I\'m ' + this.name.first + '.');
};

All JavaScript objects inherit properties and methods from a prototype:

  • Date objects inherit from Date.prototype

  • Array objects inherit from Array.prototype

  • Person objects inherit from Person.prototype

The Object.prototype is on the top of the prototype inheritance chain:

Date objects, Array objects, and Person objects inherit from Object.prototype.

Name all the ways of extending objects

  • Object.create

  • Object.setPrototypeOf

  • __proto__

  • Prototype

  • class syntax

  • copying fields

Last updated