//JavaScript完美甘露模型代码
function Class() {
var aDefine = arguments[arguments.length-1];
if(!aDefine) return;
//解析基类
var aBase = arguments.length > 1?arguments[0]:object;
//临时函数,用于挂接原型链
function prototype_() {};
//准备传递基类
prototype_.prototype = aBase.prototype;
//建立类要用的prototype
var aPrototype = new prototype_();
//复制类定义到当前的prototype
for(var menber in aDefine)
//构造函数不用复制
if (menber!="Create")
aPrototype[menber] = aDefine[menber];
//根据具体是否继承特殊属性和性能情况,分别注释下列语句
if(aDefine.toString != Object.prototype.toString)
aPrototype.toString = aDefine.toString;
if(aDefine.toLocaleString != Object.prototype.toLocaleString)
aPrototype.toLocaleString = aDefine.toLocaleString;
if(aDefine.valueOf != Object.prototype.valueOf)
aPrototype.valueOf = aDefine.valueOf;
//若有构造函数
if(aDefine.Create) {
var aType = aDefine.Create;
}else
aType = function() {
//调用基类的构造函数
this.base.apply(this,arguments);
};
//设置类的prototype
aType.prototype = aPrototype;
//设置类型关系,以便追溯继承关系
aType.Base = aBase;
//为本类对象扩展一个Type属性
aType.prototype.Type = aType;
//返回构造函数作为类
return aType;
};
//根类object定义
//定义小写的object根类用于实现最基础的方法
function object() {};
object.prototype.isA = function(aType) {
var self = this.Type;
while(self) {
if(self == aType) return true;
self = self.Base;
};
return false;
};
//调用基类构造函数
object.prototype.base = function() {
//获取当前对象的基类
var Base = this.Type.Base;
//若基类已经没有基类
if(!Base.Base){
Base.apply(this,arguments);
}else {
//若基类还有基类
//1.先覆写字this.base
this.base = MakeBase(Base);
//2.再调用基类的构造函数
Base.apply(this,arguments);
//3.删除覆盖的base属性
delete this.base;
};
//包装基类的构造函数
function MakeBase(Type) {
var Base = Type.Base;
//如果基类已无基类,则无需包装
if(!Base.Base) return Base;
//否则应用临时变量Base的构造函数
return function() {
//1.先覆写this.base
this.base = MakeBase(Base);
//2.再调用基类的构造函数
Base.apply(this,arguments);
};
};
};
/**
*
*====================使用=========================
*/
var Person = Class({
Create : function(name,age) {
//调用上层构造函数
this.base();
this.name = name;
this.age = age;
},
SayHello : function() {
alert("Hello I‘m " + this.name + "," + this.age + "years old!");
},
toString : function() {
//覆写tostring方法
return this.name;
}
});
var Employee = Class(Person,{
Create : function(name,age,salary) {
//调用基类的构造函数
this.base(name,age);
this.salary = salary;
},
ShowMeTheMoney : function() {
alert(this.toString() + "$" + this.salary);
}
});
var xijinping = new Person("xijinping",63);
var likeqiang = new Employee("likeqiang",55,3500);