1. prototype實(shí)現(xiàn)繼承
function Human(name){
this.name=name
}
Human.prototype.run=function(){
console.log('跑')
}
function Man(name){
Human.call(this,name)
this.gender='男'
}
function f(){}
f.prototype=Human.prototype
Man.prototype=new f()
Man.prototype.constructor=Man
由于IE不支持Man.prototype.proto=Human.prototype這種寫法,所以我們通過創(chuàng)建一個(gè)空的構(gòu)造函數(shù)爆存,讓這個(gè)函數(shù)的prototype指向Human.prototype健蕊,然后讓Man.prototype等于這個(gè)空函數(shù)的實(shí)例匠题,實(shí)現(xiàn)了原型鏈的繼承边涕。
2. class繼承
class Human{
constructor(name){
this.name=name
}
run(){
console.log('跑')
}
}
class Man extends Human{
constructor(name){
super(name)
this.gender='男'
}
fight(){
console.log('打架')
}
}
這種寫法的優(yōu)點(diǎn)是寫起來(lái)比上面方便,缺點(diǎn)是原型鏈上的屬性值只能是函數(shù)衍锚。