js中用es5实现继承那些事看这一篇就够了
用es6语法实现继承很简单,用extends就够了,然而很多人不怎么理解如何在es5中实现,或者知道的方法不全,一共有5种方式,接下来让我们逐一击破
- 借助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上的方法(部分继承)
- 借助原型链
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]
缺点:两个实例使用的是同一原型对象
- 组合继承
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())
- 优化组合继承
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以及实例对象,原型对象,构造函数不清楚,请点击查看这篇文章
- 寄生组合继承(最后版本)
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