1.call或apply
function Cat(name,color){
Animal.call(this);//改變一個(gè)Animal的指向
this.name = name;
this.color = color;
}
var cat1 = new Cat("大毛","黃色");
alert(cat1.species); // 動(dòng)物
這種辦法的缺點(diǎn)是只能拿到構(gòu)造函數(shù)內(nèi)部的屬性和方法(即只能拿到私有屬性)
2.使用prototype屬性
Cat.prototype = new Animal();//Animal里的prototype屬性的對(duì)象和方法會(huì)被實(shí)例對(duì)象繼承
Cat.prototype.constructor = Cat;//每一個(gè)實(shí)例對(duì)象都有一個(gè)constructor屬性指向它的構(gòu)造函數(shù),要將Animal的改為Cat
var cat1 = new Cat("大毛","黃色");
alert(cat1.species); // 動(dòng)物
缺點(diǎn):把私有的和公共的全部放在了子構(gòu)造函數(shù)的原型對(duì)象
3.第二種方法的改進(jìn)秩命,直接將prototype賦值
Cat.prototype = Animal.prototype;
Cat.prototype.constructor = Cat;
var cat1 = new Cat("大毛","黃色");
alert(cat1.species); // 動(dòng)物
缺點(diǎn):存在引用關(guān)系密浑,相當(dāng)于淺拷貝
4.利用空對(duì)象作為中介(最終選擇的)
var F = function(){};
F.prototype = Animal.prototype;
Cat.prototype = new F();
Cat.prototype.constructor = Cat;
F是空對(duì)象,所以幾乎不占內(nèi)存。這時(shí),修改Cat的prototype對(duì)象,就不會(huì)影響到Animal的prototype對(duì)象格嗅。
允許父級(jí)影響子集,不允許子集影響父級(jí)
5.拷貝繼承
function extend2(Child, Parent) {
var p = Parent.prototype;
var c = Child.prototype;
for (var i in p) {
c[i] = p[i];
}
}
利用for循環(huán)將子元素一個(gè)一個(gè)拷貝祸泪,深拷貝吗浩,這種方法在復(fù)雜的時(shí)候不適用