標籤:將不 需要 console this animal tor 資料 arguments 構造
function animale(){
this.species ="貓科";
}
function cat(){
this.name=name;
this.color=color
}
1:基於apply()方法和call()方法
在子項目中加入一行代碼
function cat(){
this.name=name;
this.color=color;
animale.apply(this,arguments); //這裡的this就是指當前調用對象
}
var cat1=new cat("大黃","白色");
var cat2=new cat("戈薇","灰色");
console.log(cat1.species);
console.log(cat2.species);
缺點:不能調用父類原型類中的方法和屬性
eg:animale.prototype.show=function(){alert(this.color)}
cat1.show();>-----undefined
2:基於原型的繼承
cat.prototype=new animale(); //定義玩這句後cat.prototype.constructor就指向了animale
cat.prototype.constructor=cat;
var cat3 =new cat("大黃","白色");
var cat2=new cat("戈薇","灰色");
console.log(cat2.species);
//可以訪問animale原型中的方法和屬性,但是不能直接存取父類的建構函式,第一代改變了父類的參考型別的值,其他的子代也會改變,但基本類型的值不會隨著改變。
eg:cat3.species="犬科";
console.log(cat2.species); >-----貓科
3:利用空媒介進行封裝處理(基於直接用原型繼承的改變)
我們將不需要變化的資料放到父類 的原型裡面
animale.prototype.species="貓科"
function f(){} //空函數,F是Null 物件,所以幾乎不佔記憶體
f.prototype=animale.prototype;
cat.prototype = new f();
cat.prototype.constructor =cat;
我們在把上述代碼通過一個函數進行封裝
function excent(child,parent){
var F=function(){}
F.prototype=parent.prototype;
child.prototype=new F();
child.prototype.constructor=child;
}
excent(cat,animale);
var cat1 = new Cat("大毛","黃色");
alert(cat1.species); // 動物
js的建構函式繼承的幾種類型