方法2基本上是方法1的封装,提供了一个专门的方法用于子类的继承,同时克服了方法1的两个缺点:
// namespace
JsDev = {};
JsDev.extend = function(subClass, baseClass) {
function inheritance() {}
inheritance.prototype = baseClass.prototype;
subClass.prototype = new inheritance(); // 改变子类的原型,使其原型与父类原型串连起来
subClass.prototype.constructor = subClass; // 改变子类的构造函数
subClass.baseConstructor = baseClass; // 保存对基类构造函数的引用,以便在子类中调用
subClass.superClass = baseClass.prototype; // 保存对父原型的引用
}
//Person class
function Person(first, last) {
this.first = first;
this.last = last;
}
Person.prototype.toString = function() {
return this.first + " " + this.last;
};
//Employee class
function Employee(first, last, id) {
Employee.baseConstructor.call(this, first, last); // 调用父类中的构造函数
this.id = id;
}
// subclass Person
JsDev.extend(Employee, Person);
Employee.prototype.toString = function() {
return Employee.superClass.toString.call(this) + ": " + this.id; // 调用父类中被覆盖的同名方法
};
//Manager
function Manager(first, last, id, department) {
Manager.baseConstructor.call(this, first, last, id);
this.department = department;
}
// subclass Employee
JsDev.extend(Manager, Employee);
Manager.prototype.toString = function() {
return Manager.superClass.toString.call(this) + ": " + this.department;
};