Several ways of js inheritance

Posted by a.heresey on Sun, 12 May 2019 05:29:08 +0200

How to implement JS inheritance:

Now that we want to achieve inheritance, we first have to have a parent class, the code is as follows:

function Animal(name) {
      // attribute
      this.name = name || 'Xiao Bai';
      // Example method
      this.sleep = function () {
        console.log(this.name + 'Sleeping in!');
      }
      //Instance Reference Properties
      this.features = ['11', '22'];
    }
    // Prototyping method
    Animal.prototype.eat = function (food) {
      console.log(this.name + 'I am eating:' + food);
    };

1. Inheritance of Prototype Chain

Core: Prototype parent class instances as subclasses

 


   function Cat(name) {}
    //hold Cat Prototype orientation Animal
    Cat.prototype = new Animal();
    var tom = new Cat('Tom');
    var kissy = new Cat('Kissy');

    console.log(tom.name); // "Xiao Bai"
    console.log(kissy.name); // "Xiao Bai"
    console.log(tom.features); // ["11", "22"]
    console.log(kissy.features); // ["11", "22"]

    tom.name = 'Small black';
    tom.features.push('33');

    //For parent instance value type member changes, no impact
    console.log(tom.name); // "Small black"
    console.log(kissy.name); // "Xiao Bai"
    //Changes in the reference type members for parent instances can affect other subclass instances by affecting other subclass instances
    console.log(tom.features); // ["11", "22", "33"]
    console.log(kissy.features); // ["11", "22", "33"]
Characteristic:
1. Very pure inheritance relationship. Instances are instances of subclasses and also instances of parent classes.
2. The parent class adds new prototype methods/prototype attributes, which can be accessed by subclasses.
3. Simple and easy to implement
Disadvantages:
1. Instance attributes can be added to Cat instances in the Cat constructor. If you want to add prototype attributes and methods, you must execute them after statements like new Animal().
2. All attributes from prototype objects are shared by all instances (reference attributes from prototype objects are shared by all instances) (see Appendix Code for details: Example 1)
3. When creating subclass instances, you cannot pass parameters to the parent constructor
 

2. Constructional Inheritance

Core: Using constructors of parent classes to enhance subclass instances is equivalent to copying instance attributes of parent classes to subclasses (prototypes are not used)

function Cat(name) {
      Animal.call(this);
      this.name = name || 'Small black';
    }
    var cat = new Cat();
    var animl = new Animal();
    console.log(cat.name);//Small black
    cat.sleep();//Xiao Hei is sleeping in.
    console.log(animl.name);//Xiao Bai
    animl.name = 'Chinese rhubarb';
    console.log(animl.name);//Chinese rhubarb
    cat.sleep();//Xiao Hei is sleeping in!
    console.log(cat.name);//Small black
    console.log(cat instanceof Animal); // false
    console.log(cat instanceof Cat); // true
Characteristic:
1. Solve the problem that in 1, subclass instances share parent class reference attributes.
2. When creating subclass instances, you can pass parameters to the parent class
3. Multiple inheritance can be achieved (call multiple parent objects)
Disadvantages:
1. Instances are not instances of parent classes, but instances of subclasses.
2. Only instance attributes and methods of parent class can be inherited, but prototype attributes/methods can not be inherited.
3. Function reuse cannot be realized. Each subclass has a copy of its parent instance function, which affects its performance.
 

3. Instance Inheritance

Core: Adding new features to parent instances and returning them as child instances

function Cat(name) {
      var instance = new Animal();
      instance.name = name || 'Small black';
      return instance;
    }
    var cat = new Cat();
    console.log(cat.name);//Small black
    cat.sleep();//Xiao Hei is sleeping in!
    cat.features.push('33')
    console.log(cat.features);//["11", "22", "33"]
    console.log(cat instanceof Animal); // true
    console.log(cat instanceof Cat); // false
Characteristic:
1. There is no restriction on the mode of invocation. Whether it is a new subclass () or a subclass (), the returned objects have the same effect.
Disadvantages:
1. Instances are instances of parent classes, not subclasses
2. Multiple inheritance is not supported

4. Copy Inheritance

Core: Copy every object of the parent class through the for loop

//Go through the cycle copy Each item of the parent class
    function Cat(name) {
      var animal = new Animal();
      for (var p in animal) {
        Cat.prototype[p] = animal[p];
      }
      Cat.prototype.name = name || 'Small black';
    }

    var cat = new Cat();
    console.log(cat.name);//Small black
    cat.sleep();//Xiao Hei is sleeping in!
    console.log(cat instanceof Animal); // false
    console.log(cat instanceof Cat); // true
Characteristic:
1. Supporting multi-inheritance
Disadvantages:
1. Low efficiency and high memory usage (because you want to copy the attributes of the parent class)
2. Unable to obtain non-enumerable methods of the parent class (non-enumerable methods, not accessible using for in)
 

5. Combinatorial Inheritance

Core: By calling the parent class structure, inheriting the properties of the parent class and retaining the merits of parameter transfer, and then by using the parent class instance as the prototype of the child class, function reuse is realized.

function Person(name, age, sex) {
            this.name = name;
            this.age = age;
            this.sex = sex;
        }
        Person.prototype.sayHi = function () {
            console.log("I am Person Method");
        };
        function Student(name, age, sex, score) {
            //Borrowing constructors:The problem of duplication of attribute values
            Person.call(this, name, age, sex);
            this.score = score;
        }
        //Changing the Orientation of Prototype----inherit
        Student.prototype = new Person(); //No passing value
        //Change the orientation of the prototype back to the original
        Student.prototype.constructor = Student;
        Student.prototype.eat = function () {
            console.log("I am Student Method");
        };
        var stu = new Student("Small black", 20, "male", "100 branch");
        console.log(stu.name, stu.age, stu.sex, stu.score);//Xiao Hei 20 Males 100 Points
        stu.sayHi();//I am Person Method
        stu.eat();//I am Student Method
Characteristic:
1. You can inherit instance attributes/methods, or prototype attributes/methods.
2. Instances of both subclasses and parent classes
3. There is no reference property sharing problem
4. Reference
5. Function reusability
Disadvantages:
1. Two calls to the parent constructor resulted in two instances (the subclass instance masked the one on the prototype of the subclass).

Topics: Javascript Attribute