Prototypical Inheritance

  • #javascript

All JavaScript objects have a prototype that provides shared properties and methods. For example, all strings have access to the methods from String.prototype. This can be used to replicate object-oriented features such as encapsulation and inheritance.

Creating objects

Literal

const p1 = {
  name: "John"
};

Object.create

Creates a new object with its prototype set to the given object.

const p1 = {
  name: "John"
};

const p2 = Object.create(p);

p1.name // "John"
p2.name // "John"

p1.hasOwnProperty('name') // true
p2.hasOwnProperty('name') // false

Constructor

A constructor creates a new object with its prototype set to the constructor's prototype. The constructor is then called with its this context bound to that new object.

function Person(name) {
  this.name = name
}

const p1 = new Person('John');

const p2 = Object.create(Person.prototype
Person.call(p2, 'John')

Encapsulation

class Person {
  constructor(name) {
    this.name = name;
  }

  greet() {
    console.log(`Hello, my name is ${this.name}.`);
  }
}

const john = new Person('John');
john.greet(); // Hello, my name is John.
function Person(name) {
  this.name = name;
}
Person.prototype.greet = function() {
  console.log(`Hello, my name is ${this.name}.`);
};

const john = new Person('John');

john.greet(); // Hello, my name is John

Inheritance

class Employee extends Person {
  constructor(name, job, employer) {
    super(name);

    this.job = job;
    this.employer = employer;
  }

  greet() {
    super.greet();
    console.log(`I am a ${this.job} at ${this.employer}.`);
  }
}

const bill = new Employee('Bill', 'cashier', 'Woolworths');
bill.greet();
// Hello, my name is Bill.
// I am a cashier at Woolworths.
function Employee(name, job, employer) {
  Person.call(this, name);

  this.job = job;
  this.employer = employer;
}
Employee.prototype = Object.create(Person.prototype);
Employee.prototype.constructor = Employee;

Employee.prototype.greet = function() {
  Person.prototype.greet.call(this);
  console.log(`I am a ${this.job} at ${this.employer}.`);
};

const bill = new Employee('Bill', 'cashier', 'Coles');

bill.greet();
// Hello, my name is Bill.
// I am a cashier at Coles.