狗类继承动物类

300 阅读1分钟

示例代码


<script>

    // 动物构造方法,作为父类
    function Animal(hp) {
        this.hp = hp
    }

    // 定义了共用的方法
    Animal.prototype.breath = function () {
        alert("呼吸");
    }

    // 狗构造方法,作为子类
    function Dog(hp) {
        Animal.call(this, hp);
    }

    // 让狗的原型等于动物的实例,相当于实现了一个继承
    Dog.prototype = new Animal();
    
    // 添加方法
    Dog.prototype.shout = function () {
        alert("狗在叫")
    }

    // 实例化对象与方法调用
    var xq = new Dog(100);
    xq.breath();
    xq.shout();

</script>

运行效果

在这里插入图片描述 在这里插入图片描述