原型链继承
利用原型链来继承父级的属性和方法
缺点:所有属性和方法都是共享的且无法传参
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