关于ES6类的继承自己的一些见解和总结

一丶前三种继承方式

    1. 原型链继承(代码如下) 
    // 缺点: 原型上的数据共享,所以原型创建的实例数据会互相影响

    const Parent_1 = function () {}

    Parent_1.prototype.getName = function () {
        return '宋';
    }

    const Child_1 = function () {}

    Child_1.prototype = new Parent_1()

    // child 的原型是 ChildClass_1, ChildClass_1 的原型是 ParentClass_1

    const child_1 = new Child_1();  



    2. 借助构造函数继承(代码如下) 
    // 说白了就是利用call和apply改变this指向,使父类的this指向子类即可
    // 优点: 实例之间的数据不会互相影响
    // 缺点: 无法继承父类的原型, 每实例化一个对象之后都会重新创建一遍这些方法,占用内存空间

    const Parent_2 = function () {
        this.name = '高'
    }
    Parent_2.prototype.getName = function () {
        return this.name;
    }
    Parent_2.prototype.sex = "男"

    const Child_2 = function () {
        this.age = 26;
        Parent_2.call(this);
    }

    // 实例之间的数据不会互相影响,但是拿不到父类在原型上定义的属性和方法
    const child_2 = new Child_2()
    const child_3 = new Child_2()


    3.组合式继承(代码如下)
    // 缺点: 每实例化一个对象之后都会重新创建一遍这些方法,占用内存空间

    const Parent_3 = function () {
        this.name = '高'
    }

    Parent_3.prototype.getName = function () {
        return this.name;
    }

    Parent_3.prototype.sex = "男"

    const Child_3 = function () {
        this.age = 26;
        Parent_3.call(this);
    }

    // 使得子类的原型指向父类的原型,从而保障子类得到父类在原型上定义的属性和方法
    Child_3.prototype = Parent_3.prototype

    // 实例之间的数据不会互相影响,并且能拿到父类在原型上定义的属性和方法
    const child_4 = new Child_3()
    const child_5 = new Child_3()

另外的一种就是目前来说最完美的方法了

寄生组合式继承:

    const Parent_1 = function () {
        name = '宋'
    }

    Parent_1.prototype.getName = function () {
        return this.name;
    }
    
    const TempFun = function () {}

    TempFun.prototype = Parent_1.prototype;

    const Child_1 = function () {
        Parent_1.call(this)
    }

    Child_1.prototype = new TempFun ()
    
    // 应用
    const child_1 = new Child_1();  

说白了其实就可以理解成创建一个寄生体,这个寄生体只有原型函数的原型链上的方法和属性,这样一来就大大的减少了性能损耗

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值