js的几种继承方式

本文探讨了JavaScript中的类继承,包括基本的类表示、组合继承、寄生组合继承和ES6的`extends`关键字。重点讲解了组合继承的优缺点,并通过寄生组合继承优化了内存使用。最后介绍了ES6的类继承机制,强调了`super`关键字的作用。

首先先来讲下,其实在JS中并不存在类,class只是语法糖,本质还是函数

class Person {}
Person instanceof Function // true

组合继承

function Parent(value) {
    this.val = value
}

parent.prototype.getValue = function() {
    console.log(this.val);
}

function Child(value) {
    Parent.call(this, value)
}

Child.prototype = new Parent()

const child = new Child(1)

child.getValue() //1
child instanceof Parent //true

以上继承方式的核心是在子类的构造函数中通过Parent.call(this) 继承父类的属性,然后改变子类的原型为new parent()来继承父类的函数。

这种继承方式的优点在于构造函数可以传参,不会与父类引用属性共享,可以复用父类的函数,但是也存在一个缺点就是在继承父类函数的时候调用了父类构造函数,导致子类的原型多了不需要的父类属性,存在内存上的浪费

寄生组合继承

这种继承方式对组合继承进行了优化,组合继承缺点在于继承父类函数是调用了构造函数,我们只需要优化掉这点就行了

function Parent(value) {
    this.val = value
}

Parent.prototype.getValue = function() {
    console.log(this.val)
}

function Child(value) {
    Parent.call(this, value)
}

Child.prototype = Object.create(Parent.prototype, {
    constructor: {
        value: Child,
        enumerable: false,
        writable: true,
        configurable: true
    }
})

const child = new Child(1)

child.getValue() // 1
child instanceof Parent //true

ES6 extends继承

class Parent {
    constructor(value) {
        this.val = value
    }
    getValue() {
        console.log(this.val);
    }
}
class Child extends Parent {
    constructor(value) {
        super(value)
        this.val = value
    }
}
let child = new Child(1)
child.getValue() // 1
child instanceof Parent // true

 

class实现继承的核心在于使用extends表明继承哪个父类,并且在子类构造函数中必须调用super,因此这段代码可以看成Parent.call(this, value)

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值