组合继承

作者: 杰克_王_ | 来源:发表于2019-10-20 14:13 被阅读0次
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>组合继承</title>
    </head>
    
    <body>
        <script>
            function Animal(category) {
                this.category = category || "Animal";
            }
    
            Animal.prototype.run = function () {
                console.log("Animal run");
            }
    
            function Dog(category, name) {
                Animal.call(this, category); // 继承示例属性
                // Animal.apply(this, [category]);
                this.name = name || 'dog';
                this.type = 'dog';
            }
    
            Dog.prototype = Object.assign({}, Animal.prototype); // 继承原型方法,修改不会同步继承
            // Dog.prototype = Object.create(Animal.prototype); // 继承原型方法,修改会同步继承
            Dog.prototype.constructor = Dog; // 复原原型指向
    
            var dog = new Dog("dog", "小白");
    
            Animal.prototype.walk = function () {
                console.log("Animal walk");
            }
    
            console.log(dog);
    
            for (var name in Animal.prototype) {
                console.log(name);
                console.log(Animal.prototype[name]);
            }
        </script>
    </body>
    
    </html>
    

    相关文章

      网友评论

        本文标题:组合继承

        本文链接:https://www.haomeiwen.com/subject/jvtamctx.html