继承:组合继承(原型继承与借用构造函数):用构造函数实现对实例属性的继承,用原型链实现对原型属性和方法的继承
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();