javascript 中的几种继承方式

原型链继承

function Parent(){}
const parent = new Parent()
Child.prototype = parent
function Child(){}
​
Child.prototype.name = 'sun'
const child = new Child()
console.log(child)
console.log(parent)

特点

1、来自原型对象的所有属性被所有实例共享,即,改变 Child.prototype.name,Parent.prototype.name 同时被改变了,不满足隔离性。

2、创建子类实例时,无法向父类构造函数传参。

 

构造函数继承

function Parent(){}
function Child(){
    Parent.call(this)
}
​
Child.prototype.name = 'sun'
const parent = new Parent()
const child = new Child()
console.log(child)
console.log(parent)

特点

1、解决了原型链继承方式的子类共享父类原型对象的问题。

2、解决了原型链继承方式无法向父类构造函数传参问题。

3、不能继承父类原型属性

 

寄生组合继承 / 圣杯模式

function Parent(){}
function Child(){}
function Buffer(){}
​
Buffer.prototype = Parent.prototype
const buffer = new Buffer()
Child.prototype = buffer
​
Child.prototype.name = 'sun'
const parent = new Parent()
const child = new Child()
console.log(child)
console.log(parent)

特点

1、堪称完美,但较为复杂。

 

类的继承

class Parent {}
class Child extends Parent {}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值