javascipt

原型继承

2019-10-20  本文已影响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";
            this.arry = ['a', 'b', 'c'];
        }

        function Dog(name) {
            this.name = name;
            this.type = 'dog';
        }

        // 缺点
        // 1. 想为子类添加新的属性或方法,必须放在 new Animal之后
        // 2. 无法实现多继承
        // 3. 原型链被破坏
        // 4. 无法向父级传参
        // 5. 引用类型的属性会被影响,比如数组对象会修改到原型上
        Dog.prototype = new Animal();

        // Dog.prototype.speak = function () {
        //     console.log('speak');
        // }

        var dog = new Dog('小白');
        // dog.speak();
        dog.arry.push('d');
        console.log(dog);
    </script>
</body>

</html>
上一篇 下一篇

猜你喜欢

热点阅读