JavaScript中的继承——组合继承。

组合继承

//动物类
    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 Cat(name,sex){
    
    
        //构造继承
        Animal.call(this,name,sex);
    }

    //原型链继承
    Cat.prototype=new Animal();

    var cat=new Cat('小花','公');
    console.log(cat);

    cat.eat();

    console.log(cat instanceof Animal);//true
    console.log(cat instanceof  Cat);//true

特点
原型链继承和构造继承,相互弥补缺点。

缺点
里面存在两个实例,消耗内存。

猜你喜欢

转载自blog.csdn.net/weixin_46953330/article/details/118636678