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 Mouse(){
    
    
        var animal=new Animal();

        return animal;
    }
    //下面这种写法可以使用
    //var mouse=new Mouse();
    var mouse=Mouse();
    console.log(mouse);

    //实例继承  子类的实例不是本身  是父类
    console.log(mouse instanceof  Mouse);//false
    console.log(mouse instanceof  Animal);//true

优点:
不限制调用方式(不管是new 还是 直接调用函数执行)

缺点:
不支持多继承。

猜你喜欢

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