繼承:組合繼承(原型繼承與借用構造函數):用構造函數實現對實例屬性的繼承,用原型鏈實現對原型屬性和方法的繼承
function Super(name) {
this.name = name;
this.colors = ["yellow", "red"];
}
Super.prototype.sayName = function() {
alert(this.name);
}
function Sub(name, age) {
Super.call(this, name); // 第二次調用Super
this.age = age;
}
Sub.prototype = new Super(); // 第一次調用Super
Sub.prototype.constructor = Sub;
Sub.prototype.sayAge = function() {
alert(this.age);
}
var instance1 = new Sub("Hello Kitty", 20);
instance1.colors.push("green");
console.log("1:",instance1.colors);
instance1.sayName();
instance1.sayAge();
var instance2 = new Sub("LiLei", 30);
console.log("2:",instance2.colors);
instance2.sayName();
instance2.sayAge();
問題:父類構造函數調用了兩次,解決此問題,採用寄生組合式繼承
寄生組合式繼承:--最常用的繼承方式
function object(o) { // 創建對象的副本
function F() {
}
F.prototype = o;
return new F();
}
function inheritPrototype(Sub, Super) {
var protype = object(Super.prototype);
protype.constructor = Sub;
Sub.prototype = protype;
}
function Super(name) {
this.name = name;
this.colors = ["yellow", "red"];
}
Super.prototype.sayName = function() {
alert(this.name);
}
function Sub(name, age) {
Super.call(this, name); // 第二次調用Super
this.age = age;
}
inheritPrototype(Sub, Super);
Sub.prototype.constructor = Sub;
Sub.prototype.sayAge = function() {
alert(this.age);
}
var instance1 = new Sub("Hello Kitty", 20);
instance1.colors.push("green");
console.log("1:",instance1.colors);
instance1.sayName();
instance1.sayAge();
var instance2 = new Sub("LiLei", 30);
console.log("2:",instance2.colors);
instance2.sayName();
instance2.sayAge();