继承
原型链
function SuperType() {
this.property = true;
}
SuperType.prototype.getSuperValue = function() {
return this.property;
};
function SubType() {
this.subproperty = false;
}
// 继承了 SuperType
SubType.prototype = new SuperType();
SubType.prototype.getSubValue = function() {
reurn this.subproperty;
}
var instance = new SubType();
alert(instance.getSuperValue());
原型链的问题
- 最主要的问题来自包含引用类型值的原型;
- 不能向超类的构造函数中传递参数。
借用构造函数
function SuperType() {
this.colors = ["red", "bule", "green"];
}
function SubType() {
// 继承了SuperType
SuperType.call(this);
}
var instance1 = new SubType();
借用构造函数的问题
和构造函数模式存在一样的问题–无法实现方法复用。
组合继承
function SuperType(name) {
this.name = name;
this.colors = ["red", "bule", "green"];
}
SuperType.prototype.sayName = function() {
alert(this.name);
};
function SubType(name, age) {
// 继承属性
SuperType.call(this, name);
this.age = age;
}
// 继承方法
SubType.prototype = new SuperType();
SubType.prototype.constructor = SubType;
SubType.prototype.sayAge = function() {
alert(this.age);
}
var instance1 = new SubType("Nicholas", 29);
原型式继承
function object(o) {
function F(){}
F.prototype = o;
return new F();
}
var Person = {
name: "Nicholas",
friends: ["Shelby", "Court", "Van"]
};
var anotherPerson = object(person);
Object.create()方法规范化了原型式继承。
寄生式继承
function createAnother(original) {
var clone = Object.create(original);
clone.sayHi = function() {
alert("hi");
}
return clone;
}
var person = {
name: "Nicholas",
friends: ["Shelby", "Court", "Van"]
}
var anoterPerson = createAnother(person);
寄生组合式继承
组合继承存在的问题:调用两次构造函数。寄生组合式继承就是解决这个问题的方案。
function inheritPrototype(subType, superType) {
var prototype = Object.create(superType.prototype); // 创建对象
prototype.constructor = subType; // 增强对象
subType.prototype = prototype; // 指定对象
}
function SuperType(name) {
this.name = name;
this.colors = ["red", "bule", "green"];
}
SuperType.prototype.sayName = function() {
alert(this.name);
};
function SubType(name, age) {
// 继承属性
SuperType.call(this, name);
this.age = age;
}
inheritPrototype(SubType, SuperType);
SubType.prototype.sayAge = function() {
alert(this.age);
}
var instance1 = new SubType("Nicholas", 29);