借用構(gòu)造函數(shù)(偽造對(duì)象或經(jīng)典繼承)
基本思想:在子類型構(gòu)造函數(shù)的內(nèi)部調(diào)用超類型的構(gòu)造函數(shù)
優(yōu)點(diǎn): 相比原型鏈而言,借用構(gòu)造函數(shù)有一個(gè)很大的優(yōu)勢(shì)孩擂,就是子類型函數(shù)構(gòu)造函數(shù)可以向超類型構(gòu)造函數(shù)傳遞參數(shù)
缺點(diǎn): 方法都在構(gòu)造函數(shù)中定義类垦,因此函數(shù)的復(fù)用性就無從談起了
function Animal(speices){
this.speices = speices;
}
function Dog(){
Animal.call(this,'中華田園犬'); // dog擁有了animal中的name屬性
}
var dog1 = new Dog();
var dog2 = new Dog();
console.log(dog1.speices); // 中華田園犬
組合繼承(原型鏈+借用構(gòu)造函數(shù))
- 基本思想: 原型鏈實(shí)現(xiàn)對(duì)原型屬性和方法的繼承城须,而通過借用構(gòu)造函數(shù)來實(shí)現(xiàn)對(duì)實(shí)例屬性的繼承
- 優(yōu)點(diǎn): 在原型上定義方法是實(shí)現(xiàn)了函數(shù)復(fù)用,又能偶保證每個(gè)實(shí)例都有它自己的屬性
function Animal(speices){
this.speices = speices;
this.skills = ["jump","climb","catch","run"]
}
Animal.prototype.getSpeices = function(){
console.log(this.speices)
}
function Dog(speices,color){
// 借用構(gòu)造函數(shù)繼承砰琢,繼承父類的屬性
Animal.call(this,speices);
this.color = color;
}
// 原型繼承陪汽,繼承父類的方法
Dog.prototype = new Animal();
Dog.prototype.getColors = function(){
console.log(this.colors);
}
var dog1 = new Dog('博美','white');
dog1.skills.push('acting');
console.log(dog.skills); // ["jump","climb","catch","run","acting"]
dog1.getSpeices(); // 博美
var dog2 = new Dog('柯基','brown');
console.log(dog2.skills); // ["jump","climb","catch","run"]
dog2.getSpeices(); // 柯基
組合繼承融合借用構(gòu)造函數(shù)(屬性繼承)和原型鏈繼承(方法繼承)的優(yōu)點(diǎn)莺褒,使實(shí)例都有自己的屬性遵岩,又能共享統(tǒng)一方法,成為最常用的繼承方法