基本思想
將原型鏈和借用構(gòu)造函數(shù)的技術(shù)組合到一塊掖举。
使用原型鏈實(shí)現(xiàn)對(duì)原型屬性和方法的繼承凶伙,通過(guò)借用構(gòu)造函數(shù)實(shí)現(xiàn)對(duì)實(shí)例屬性的繼承。
function SuperType(name){
this.name = name;
this.colors = ["red","blue","green"];
}
SuperType.prototype.sayName = function () {
alert(this.name);
};
function SubType(name,age){
//繼承了SuperType,同時(shí)還傳遞了參數(shù)
SuperType.call(this,name);
//實(shí)例屬性
this.age = age;
}
//繼承方法
SubType.prototype = new SuperType();
SubType.prototype.constructor = SubType;
SubType.prototype.sayAge = function () {
alert(this.age);
};
var instance1 = new SubType("Wonder",23);
instance1.colors.push("black");
alert(instance1.colors); //red,blue,green,black
instance1.sayName(); //Wonder
instance1.sayAge(); //23
var instance2 = new SubType("Abby",29);
alert(instance2.colors); //red,blue,green
instance2.sayName(); //Abby
instance2.sayAge(); //29