function prototypeInstance(superType) {
function F(){}
F.prototype = superType.prototype;
return new F();
}
function inheritPrototype(subType, superType) {
var prototypeIns = prototypeInstance(superType);
prototypeIns.constructor = subType;
subType.prototype = prototypeIns;
}
function SuperType(name) {
this.name = name;
this.colors = ["red","blue","green"];
}
function SubType(name, age) {
// 继承 SuperType 属性
SuperType.call(this, name);
this.age = age;
}
inheritPrototype(SubType, SuperType);
在《你不知道的Javascript》中的另一种方案:
var task = {
setID: function(id) { this.id = id; },
outputID: function() { console.log(this.id) };
};
// 让 SubTask 委托 Task
var subTask = Object.create(task);
subTask.prepareTask = function(id, label) {
this.setID(id);
this.label = label;
}
subTask.outputTaskDetails = function() {
this.outputID();
console.log(this.id);
}
总结:前者面向类,后者编码风格称为‘对象关联’。