继承的几种方法

原型链继承

利用原型链来继承父级的属性和方法

缺点:所有属性和方法都是共享的且无法传参
function Dog(){
	this.name = '旺财'
	this.color =['黄色'],
	this.bark = function(){
		console.log('汪汪汪')
	}
}

function Animate(){}
Animate.prototype = new Dog()
Animate.prototype.constructor = Animate;

const animate1 = new Animate()
const animate2 = new Animate()
animate2.color.push('绿色')
console.log(animate1.color) // ['黄色','绿色']

构造函数继承

利用调用构造函数来继承

缺点:无法继承父级的方法
function Dog(args){
	this.name = '旺财'
	this.color =['黄色']
}
Dog.prototype.bark = function(){
	console.log('汪汪汪')
}

function Animate(args){
	Dog.call(this,args)
}

const animate = new Animate('arg')
animate.bark() // 报错

组合继承

利用调用构造函数来继承属性 利用原型链继承方法

缺点:调用两次构造函数
function Dog(args){
	this.name = '旺财'
	this.color =['黄色']
}
Dog.prototype.bark = function(){
	console.log('汪汪汪')
}

function Animate(args){
	Dog.call(this,args)
}

Animate.prototype = new Dog()
Animate.prototype.constructor = Animate

寄生组合继承

利用利用调用构造函数来继承属性 利用原型链继承构造函数的prototype

function Dog(args){
	this.name = '旺财'
	this.color =['黄色']
}
Dog.prototype.bark = function(){
	console.log('汪汪汪')
}

function Animate(args){
	Dog.call(this,args)
}

Animate.prototype = Object.create(Dog.prototype)
Animate.prototype.constructor = Animate
  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值