js中用es5实现继承那些事看这一篇就够了

js中用es5实现继承那些事看这一篇就够了

用es6语法实现继承很简单,用extends就够了,然而很多人不怎么理解如何在es5中实现,或者知道的方法不全,一共有5种方式,接下来让我们逐一击破

  1. 借助call
function Father(){
	this.arr=[1,2,3]
}
Father.prototype.say=function() {
	console.log('hello')
}
function Son() {
	Father.call(this)
}
const s=new Son()
console.log(s.arr)  //[1,2,3]
s.say()             //报错

缺点:无法继承父级元素.prototype上的方法(部分继承)

  1. 借助原型链
function Father(){
	this.arr=[1,2,3]
}
Father.prototype.say=function() {
	console.log('hello')
}
function Son() {
}
Son.prototype=new Father()
//问题:
const s1=new Son()
const s2=new Son()
s1.arr.push(4)
console.log(s1.arr)  //[1,2,3,4]
console.log(s2.arr)  //[1,2,3,4]

缺点:两个实例使用的是同一原型对象

  1. 组合继承
function Father(){
	this.arr=[1,2,3]
}
Father.prototype.say=function() {
	console.log('hello')
}
function Son() {
	Father.call(this)
}
Son.prototype=new Father()

缺点:父级构造函数被多执行了一次(第一次:Father.call(this),第二次:Son.prototype=new Father())

  1. 优化组合继承
function Father(){
	this.arr=[1,2,3]
}
Father.prototype.say=function() {
	console.log('hello')
}
function Son() {
	Father.call(this)
}
Son.prototype=Father.prototype
const s=new Son()
console.log(s.__proto__.constructor) //Function: Father

缺点:创建出来的实例对象的__proto__.constructor指向了父级构造函数
如果你对__proto__和constructor以及实例对象,原型对象,构造函数不清楚,请点击查看这篇文章

  1. 寄生组合继承(最后版本)
function Father(){
	this.arr=[1,2,3]
}
Father.prototype.say=function() {
	console.log('hello')
}
function Son() {
	Father.call(this)
}
Son.prototype=Object.create(Father.prototype)
Son.prototype.constructor=Son
const s=new Son()
console.log(s.__proto__.constructor) //Function: Son
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值