← JavaScript Interview Questions

What is the difference between classical and prototypal inheritance?

5
1
Asked 5 years ago by Hayk Hovhannisyan

Answers

Classical Inheritance

Classical Inheritance is a mechanism in which one class can extend the methods of another class.

Key Ideas:

  1. Classes may inherit from other classes.
  2. Objects are created from classes.
  3. Classes are immutable they can not be modified at runtime.
  4. Classes my or may not support multiple inheritance (depending on the language).

Example (Java):

class Animal {
  private name;
  public Animal(String name) {
    this.name = name;
  }
  public String getName() {
    return this.name;
  }
}

class Dog extends Animal {
  
}

Dog dog = new Dog("Rex");

Prototypal Inheritance

Prototypal Inheritance is a mechanism in which an object (or a function constructor) can extend methods of another object. Every object has a prototype which is a link the parent object, this structure is called prototype chain.

Key ideas:

  1. Objects can be created from function constructors, using Object.create method or defined as object literal ({}).
  2. Prototypes can be changed at runtime.
  3. Objects can inherit from multiple prototypes.

Example (JavaScript):

function Animal(name) {
  this.name = name;
}

Animal.prototype.getName() {
  return this.name;
}

funciton Dog(name) {
  Animal.call(this, name);
}

Dog.prototype = Object.create(Animal.prototype);

const dog = new Dog("Rex");

In ES6 class keyword was added which allows to use the syntax similar to other C-like languages. But under the hood JavaScript supports only prototyple inheritance, so the example below works almost identical to example above.

Example:

class Animal {
  constructor(name) {
    this.name = name;
  }
  getName() {
    return this.name;
  }
}

class Dog extends Animal {

}

const dog = new Dog("Rex");

2
Answered 5 years ago by Hayk Hovhannisyan