原型链继承
function Animal(){}
function Dog(){}
Animal.prototype.move=function(){}
Dog.prototype=Object.create(Animal.prototype)
Dog.prototype.constructor=Dog
缺点是无法定义私有方法,而且无法向构造函数传参,如果父级构造函数上存在可更改属性,实例共享更改
构造函数继承
function Animal(name){
this.name=name
}
function Dog(name){
Animal.call(this,name)
}
缺点是无法实现函数复用,而且 call 无法调用父级构造函数原型上的方法
原型式继承
function fun(obj){
function F(){}
F.prototype=obj
return new F()
}
let parent={name:parent}
let child=fun(parent)
--------------
let child=Object.create(parent) //也能搞定
缺点和原型链继承类似
寄生继承
function fun(obj){
let clone=Object.create(obj)
clone.say=()=>{
console.log('hi')
}
return clone
}
let parent={}
let child=fun(parent)
封装了继承过程并且给新对象上新增方法
组合继承
function Animal(name){
this.name=name
}
function Dog(name){
Animal.call(this,name)
}
Dog.prototype=Object.create(Animal.prototype)
Dog.prototype.constructor=Dog
let dog=new Dog('smy')
这样一来,父级构造函数属性通过 call 拿到,父级原型上的方法通过 dog.proto =>Dog.prototype=>Dog.prototype.proto 获取,也是常用的方法