方法3是方法2的小小改进,对子类的定义方式有所改进,更像是C#中类的定义方式,也是Yahoo Library中使用的方法:
// namespace
JsDev = {};
JsDev.extend = function(subClass, baseClass, overrides) {
if( ! subClass|| ! baseClass)
{
throw new Error("inheritance error");
}
function inheritance() {}
inheritance.prototype = baseClass.prototype;
subClass.prototype = new inheritance(); // 改变子类的原型,使其原型与父类原型串连起来
subClass.prototype.constructor = subClass; // 改变子类的构造函数 与方法2的区别:去掉对基类构造函数的引用
/*subClass.baseConstructor = baseClass;*/ // 保存对基类构造函数的引用,以便在子类中调用
subClass.superClass = baseClass.prototype; // 保存对父原型的引用
if(overrides)
{
for(var i in overrides)
{
subc.prototype[i] = overrides[i];
}
}
}
//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) {
//与方法2的区别
if(first)
Employee.superClass.constructor.call(this, first, last); // 调用父类中的构造函数
Employee.baseConstructor.call(this, first, last); // 调用父类中的构造函数
this.id = id;
}
// subclass JsDev.extend(Employee, Person);
Employee.prototype.toString = function() {
return Employee.superClass.toString.call(this) + ": " + this.id; // 调用父类中被覆盖的同名方法
};
//Managerfunction
Manager(first, last, id, department) {
//与方法2的区别
if(first)
Manager.superClass.constructor.call(this, first, last, id); // 调用父类中的构造函数
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;
};
子类还可以这样定义:
//Employee class
function Employee(first, last, id) {
if(first)
Employee.superClass.constructor.call(this, first, last); // 调用父类中的构造函数
this.id = id;
}
// subclass
PersonJsDev.extend(Employee, Person,
{
toString : function()
{
return Employee.superClass.toString.call(this) + ": " + this.id; // 调用父类中被覆盖的同名方法
}, anotherMethod: function()
{
}
}
)