Inheritance in JavaScript - Structural Inheritance.

Structural inheritance

Use the constructor of the parent class to enhance the subclass. Copy the construction properties of the parent class to the child class (the prototype of the parent class cannot be copied) .

 //动物类
    function Animal(name, sex) {
    
    
        this.name = name || 'Animal';
        this.sex = sex || '未知';
        this.sleep = function () {
    
    
            console.log(this.name + "在睡觉!");
        }
    }
    //添加原型属性和方法
    Animal.prototype = {
    
    
        eat: function () {
    
    
            console.log(this.name + "在吃饭!");
        },
        play: function () {
    
    
            console.log(this.name + "在玩!");
        }
    }

    //科目类
    function Type(type) {
    
    
        this.type = type || '类型';
    }
    Type.prototype.paTree = function (args) {
    
    
        console.log(args);
    }

    function Cat(name, sex, type) {
    
    
        Animal.call(this, name, sex);
        Type.call(this, type);
    }
     var cat = new Cat('小黑', '公', '猫科');
    cat.sleep();
    console.log(cat);
    //子类的实例是本身
    console.log(cat instanceof  Cat);//true
    console.log(cat instanceof  Animal);//false
    console.log(cat instanceof  Type);//false

Features
You can pass parameters to the parent class when creating a subclass.
Multiple inheritance can be achieved.

Disadvantages
The instance of the subclass object is itself, not the parent class.
Only the construction properties and methods of the parent class can be inherited, and the prototype properties and methods cannot be inherited.
Not complete inheritance, similar to cloning, a copy of the parent class, affecting performance.

Guess you like

Origin blog.csdn.net/weixin_46953330/article/details/118636196