1.prototype的方式
//父類
function person(){?
? ? this.name= 'xg';?
? ? this.sex= 'man';?
? ? this.age= '25';?
? ? this.show= function(){?
? ? ? ? return this. name + ',' + this. sex + ',' + this. age ;?
? ? }?
}?
//子類?
function man(){?
? ? this.feature = ['beard','strong'];?
}?
man.prototype = new person();?
var one = new man();?
console.log(one.feature); //['beard','strong']?
console.log(one.name); //xg
console.log(one.sex); //man
console.log(one.age); //25
console.log(one.view()); // xg , man , 25
這種方式最簡單,只需要讓子類的prototype屬性值賦值為父類的一個實例就行了,之后就可以直接使用被繼承類的方法了础废。
2.apply的方式
//父類
function person(){?
? ? this.name= 'xg';?
? ? this.sex= 'man';?
? ? this.age= '25';?
? ? this.show= function(){?
return this.?name?+ ',' + this.?sex?+ ',' + this.?age?;
? ? }?
}?
//子類?
function man(){?
? ? person.apply(this,[])
? ? this.feature = ['beard','strong'];?
}?
var one = new man();?
console.log(one.feature); //['beard','strong']?
console.log(one.name); //xg
console.log(one.sex); //man
console.log(one.age); //25
console.log(one.view()); //?xg?,?man?,?25
如果apply參數(shù)為空冗茸,即沒有參數(shù)傳遞,則通過 new Array() 榴捡、[] 來傳遞杈女,null 無效。
但是用apply方法也還是有缺點的吊圾,為什么碧信?在js中,我們有個非常重要的運算符就是”instanceof”街夭,該運算符用來比較某個對向是否為某種類型砰碴。即(one instanceof person)的值為false。?
使用call與apply方法類似板丽,call與apply的不同就是call傳的值可以是任意的呈枉,而apply傳的剩余值必須為數(shù)組。
3.call+prototype
//父類
function person(){?
? ? this.name= 'xg';?
? ? this.sex= 'man';?
? ? this.age= '25';?
? ? this.show= function(){?
return this.?name?+ ',' + this.?sex?+ ',' + this.?age?;
? ? }?
}?
//子類?
function man(){?
? ? person.call(this,[])
? ? this.feature = ['beard','strong'];?
}?
man.prototype = new person();?
var one = new man();?
console.log(one.feature); //['beard','strong']?
console.log(one.name); //xg
console.log(one.sex); //man
console.log(one.age); //25
console.log(one.view()); //?xg?,?man?,?25
此方法埃碱,若person帶多參數(shù)猖辫,調(diào)用時需要重復傳遞參數(shù)
最完善的繼承方式: