关于js继承

1.//构造函数实现继承,缺点:无法继承父类原型链上的属性和方法

		// 父类
        function Parent1() {
            this.name = 'name';
        }
        Parent.prototype.say = function() {
            console.log('111')
        }
        // 子类
        function Child1 () {
            Parent.call(this);
            this.type = 'child';
        }

2.// 原型链实现继承,子类实例化的对象属性会相互影响

	   // 父类
        function Parent2() {
            this.name = 'parent2';
            this.play = [1, 2, 3]
        }
        // 子类
        function Child2 () {
            this.type = 'child2';
        }
        Child2.prototype = new Parent2();
        let obj1 = new Child2();
        let obj2 = new Child2();
        obj1.play.push('5')
    //此时,obj1和obj2的play属性值会一起改变,因为obj1.__proto === obj2.__proto__
  1. // 组合方式继承,缺点执行父类构造函数次数过多
//父类
        function Parent3 () {
            this.name = 'parent3';
            this.play = [1, 2, 3]
        }
        //子类
        function Child3 () {
            Parent3.call(this)
            this.type = 'child3'
        }
        Child3.prototype = new Parent3();
        let obj1 = new Child3();
        let obj2 = new Child3()
        obj1.play.push('hah');
        obj1 instanceof Child3 // true
        obj1 instanceof Parent3 // true
        obj1.constructor // Parent
  1. //优化组合方式继承,缺点实例化对象不仅是子类的实例,也是父类的实例
		//父类
        function Parent4 () {
            this.name = 'parent4';
            this.play = [1, 2, 3]
        }
        //子类
        function Child4 () {
            Parent4.call(this)
            this.type = 'child4'
        }
        Child3.prototype = Parent4.prototype;
        let obj1 = new Child4();
        let obj2 = new Child4()
        obj1.play.push('hah');
  1. //组合方式继承优化,继承最优方法
//父类
        function Parent5 () {
            this.name = 'parent5';
            this.play = [1, 2, 3]
        }
        //子类
        function Child5 () {
            Parent4.call(this)
            this.type = 'child4'
        }
        Child5.prototype = Object.create(Parent5.prototype);
        Child5.prototype.constructor = Child5;
        let obj = new Child5();
        obj instanceof Child5; // true
        obj instanceof Parent5; // true
        obj.constructor // Child5
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值