js 面向对象(2)

        // 组合方式
        function Parent3 () {
            this.name = 'Parent3';
            this.play = [1, 2, 3];
        }
        function Child3 () {
            Parent3.call(this); // 父级的构造函数执行了两次
            this.type = 'child3';
        }
        Child3.prototype = new Parent3();

        var s3 = new Child3();
        var s4 = new Child3();
        s3.play.push(4);
        console.log(s3.play, s4.play);

        // 组合继承优化1
        function Parent4 () {
            this.name = 'Parent4';
            this.play = [1, 2, 3];
        }
        function Child4 () {
            Parent4.call(this);
            this.type = 'child4';
        }
        Child4.prototype = Parent4.prototype; // 引用类型

        var s5 = new Child4();
        var s6 = new Child4();
        s5.play.push(4);
        console.log(s5, s6);
        console.log (s5 instanceof Parent4);
        console.log (s5 instanceof Child4);
        // 如何判断s5是child4的实例还是parent4的实例
        console.log (s5.constructor)
        // 从父类的原型链中继承了constructor

        // 组合继承优化2
        function Parent5 () {
            this.name = 'Parent5';
            this.play = [1, 2, 3];
        }
        function Child5 () {
            Parent4.call(this);
            this.type = 'child5';
        }
        Child5.prototype = Object.create(Parent5.prototype); // 引用类型 父子原型链隔离
        Child5.prototype.constructor = Child5; // 重写child5的构造函数
        var s7 = new Child5();
        var s8 = new Child5();
        s7.play.push(4);
        console.log(s7, s8);
        console.log (s7.constructor);
    
image.png

你可能感兴趣的:(js 面向对象(2))