通过借用构造函数来继承属性,通过原型链的混成形式来继承方法。构造函数 + 原型链。
寄生组合式继承是引用类型最理想的继承范式。
function inheritPrototype(subType, superType) {
//创建对象
var prototype = Object(superType.prototype);
//增强对象
prototype.constructor = subType;
//制定对象
subType.prototype = prototype;
}
?
函数内部的过程:
第一步,创建超类原型的一个副本;
第二步,创建的副本添加constructor属性,从而弥补因重写原型而失去的默认的constructor属性;
第三步,将新创建的对象(即副本)赋值给子类型的原型。
function SuperType(name) {
this.name = name;
this.colors = ["red", "blue", "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);
};
?
//定义
function extend(subClass,superClass){
var F = function(){};
F.prototype = superClass.prototype;
subClass.prototype = new F(); //创建超类的一个副本,本质是执行对给定对象的浅复制
subClass.prototype.constructor = subClass; //原来constructor指向superClass,现在改指成subClass本身
subClass.superclass = superClass.prototype;//加多了个属性指向父类本身以便调用父类函数
if(superClass.prototype.constructor == Object.prototype.constructor) {//新创建的属性对象会指向Object,因此要重写指向本身
superClass.prototype.constructor = superClass;
}
}
//应用
function Person(name) {
this.name = name;
}
Person.prototype.sayName = function() {
alert(this.name);
};
function Chinese(name,job) {
Person.call(this, name);
this.job = job;
}
extend(Chinese, Person);
Chinese.prototype.sayJob = function() {
alert(this.job);
};
var c = new Chinese("MirrorAvatar", "coder");
alert(c.sayName()); //MirrorAvatar
?
参考资料:
原文:http://mirroravatar.iteye.com/blog/2191183