構(gòu)造函數(shù)繼承
只會(huì)繼承構(gòu)造函數(shù)本身的屬性方法,不會(huì)繼承原型中的。
var Parent=function(){
this.name='名字',
this.func=function(){
alert('方法')
}
}
Parent.prototype={
getName:function(){
alert(this.name)
}
}
var Child=function(){
Parent.call(this)//call和apply都可以
}
// 相當(dāng)于吧父類當(dāng)成一個(gè)函數(shù)在子類中運(yùn)行,并且改變this為子類實(shí)例,這樣就相當(dāng)于拷貝了 父類中構(gòu)造函數(shù)中的屬性和方法,實(shí)現(xiàn)構(gòu)造函數(shù)繼承,但是無(wú)法繼承原型中的方法和屬性
var child=new Child()
console.log(child)
原型鏈繼承
原型和實(shí)例都可以繼承,就是子類和父類共享一個(gè)原型
var Parent=function(){
this.name='名字',
this.age=25,
this.func=function(){
alert('方法')
}
}
Parent.prototype={
getName:function(){
alert(this.name)
}
}
var Child=function(){
this.childName='子名字'
}
Child.prototype=new Parent()
var child=new Child()
console.log(child)
// 利用js原型鏈的特點(diǎn)將子類的原型等于父類的實(shí)例,那么子類在原型鏈訪問(wèn)過(guò)程中就可以訪 問(wèn)到父類的屬性和方法,問(wèn)題,多個(gè)實(shí)例共享一個(gè)原型
組合繼承 借用構(gòu)造函數(shù) + 原型式繼承
var Parent=function(){
this.name='名字',
this.age=25,
this.func=function(){
alert('方法')
}
}
Parent.prototype={
getName:function(){
alert(this.name)
}
}
var Child=function(){
Parent.call(this)
}
Child.prototype=Parent.prototype
var child=new Child()
console.log(child)
class繼承
class Parent {
constructor(name){
this.name="父類名字"
}
parentFunc(){
alert(`${this.name}-parentFunc`)
}
}
//使?extends即可實(shí)現(xiàn)繼承,更加符合經(jīng)典?向?qū)ο笳Z(yǔ)?的寫法
class Child extends Parent {
constructor(name){
super(name)//?類的constructor?定要執(zhí)?super(),以調(diào)??類的constructor
this.name=name
this.age=24
}
childFunc(){
alert(`${this.name}-childFunc`)
}
}
const child=new Child("名字")
console.log(child)