Multiple implementation methods of js inheritance

Father is the parent class, and Child is the Child class. The goal of inheritance is to allow the Child class to access the properties and methods of the parent class

function Father () {
  this.name = name
  this.age = age
  this.run = function () {
    console.log('Come on')
  }
}
function Child (name, age) {}
let tom = new Child()

1. Prototype chain inheritance

Simple and easy to understand. It is to mount the parent class on the prototype of the child class.

function Father () {
  this.run = function () {
    console.log('Come on')
  }
}
function Child (name, age) {
  this.name = name
  this.age = age
}
Child.prototype = new Father()
let tom = new Child('tom', 6)
tom.run()  // Come on
console.log(tom.name)  // tom
console.log(tom.age)     // 6

Disadvantage: multiple inheritance cannot be implemented

2. Construct inheritance (using the features of call and apply)

Use call or apply to change this direction of subclass. So as to implement the method of calling the parent class in subclass.

function Father (name, age) {
  this.name = name
  this.age = age
  this.run = function () {
    console.log('Come on')
  }
}
function Child (name, age) {
  Father.call(this, ...arguments)
}
Child.prototype = new Father()
let tom = new Child()
tom.run()  // Come on 

Disadvantage: only the instance of the parent class can be inherited, not the prototype of the parent class

3. Combination inheritance (prototype chain inheritance + Construction inheritance)

Combining the advantages of prototype chain inheritance and construction inheritance (recommended)

function Father (name, age) {
  this.name = name
  this.age = age
  this.run = function () {
    console.log('Come on')
  }
}
function Child (name, age) {
  Father.apply(this, arguments)
}
Child.prototype = new Father()
let tom = new Child('tom', 19)
tom.run()  // Come on
console.log(tom.name)
console.log(tom.age)

4. Prototype inheritance or instance inheritance

Encapsulate the function of the subclass and return the parent class. New child() -- > is equivalent to new Father(). To achieve inheritance

function Father (name) {
  this.name = name
  this.run = function () {
    console.log('Come on')
  }
}
function Child (name) {
  let instance = new Father(...arguments);
  return instance;
}

let tom = new Child('tom')
tom.run()  // Come on
console.log(tom.name)

5. Copy inheritance

The for in loop is used to loop the properties of the parent class to the prototype of the child class.

function Father () {
  this.run = function () {
    console.log('Come on')
  }
}

function Child(name){
  let father = new Father();
  for(let p in father){
    Child.prototype[p] = father[p];
  }
  Child.prototype.name = name;
}
let tom = new Child('tom')
tom.run()
console.log(tom.name)

Disadvantages: low execution efficiency

Added by shruti on Mon, 09 Dec 2019 13:35:13 +0200