JS 继承

<!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>
    <script type="text/javascript">
        //继承 利用call 变量,缺点 无法继承 prototype 方法
        var Parent = function () {
            this.name = "parent";
            this.array = [1, 2, 3];
        }
        Parent.prototype.say = function () {
            console.log('hello');
        }
        var Child1 = function () {
            Parent.call(this);
            this.age = 18;
        };
        var c1 = new Child1();
        console.log('c1', c1);
        // 利用prototype 继承 ,缺点 实例化对象 无法数据 ,父类构造函数 实例化多次
        var Child2 = function () {
            this.age = 18;
        }
        Child2.prototype = new Parent();
        var c2 = new Child2();
        c2.array.push(4);
        var c22 = new Child2();
        console.log('c2', c2);
        console.log('c22', c22);
        //组合优化
        var Child3 = function () {
            Parent.call(this);
            this.age = 18;
        }
        Child3.prototype = Object.create(Parent.prototype);
        //解决 无法区分 是哪个类所实例化
        Child3.prototype.constructor = Child3;
        var c3 = new Child3();
        c3.array.push(4);
        var c33 = new Child3();
        console.log('c3', c3);
        console.log('c33', c33);
        //c3.constructor==Child3.prototype.constructor
    </script>
</head>

<body>

</body>

</html>

 

posted @ 2018-08-27 14:13  年轻的资本!  阅读(111)  评论(0编辑  收藏  举报