On the inheritance of js

Keywords: Javascript

Definition

Chinese explanation: Generally speaking, it refers to accepting the style, culture and knowledge of the predecessors
Computer terminology explanation: inheritance can make a subclass have properties and methods of the parent class or redefine and append properties and methods, etc

Let's have a father worship

  function Animal(name) {
    this.name = name || 'animal';
    this.speak = function () {
      console.log('speak');
    }
  }
  Animal.prototype.move = function () {
    console.log('move');
  }

Prototype chain inheritance

  function Cat() {
    this.getName = function () {
      console.log(this.name);
    };
  }

  Cat.prototype = new Animal('cat1');
  var cat = new Cat();
  cat.name = 'cat2';
  console.log(cat);//The instance object has a name of cat2 and a name of cat1 on the prototype
  cat.getName();//cat2 (find the current property first, then the prototype)
  console.log(cat instanceof Cat);//true
  console.log(cat instanceof Animal);//true

There is a relationship between the parent and the child, but the child does not create a new property. The set child property does not overwrite the property on the prototype. The get property is only based on the priority of reading the current property first and then the prototype

Constructor inheritance

  function Dog(name) {
    Animal.call(this);
    this.name = name || 'doggy';
  }

  var dog = new Dog();
  console.log(dog);//Only subclass properties
  console.log(dog instanceof Dog); // true
  console.log(dog instanceof Animal); // false

In fact, we just use the parent constructor to add the subclass properties. There is no relationship between the parent and the child

ES6 inheritance (perfect inheritance)

  class Animal2 {
    constructor(name) {
      this.name = name || 'animal2';
      this.speak = function () {
        console.log('speak');
      }
    }
  }

  Animal2.prototype.move = function () {
    console.log('move');
  }
  var animal2 = new Animal2('god2');
  console.log(animal2);

  class Bird extends Animal2 {
    getName() {
      console.log(this.name);
    }
  }

  var bird = new Bird('bird');
  console.log(bird);//There are properties of the parent class, and the prototype chain also points to the parent class
  bird.getName();
  console.log(bird instanceof Bird); // true
  console.log(bird instanceof Animal2); // true

Posted by starnol on Sat, 09 Nov 2019 13:01:08 -0800