日期:2014-05-16 浏览次数:20391 次
function Class(){ var aDefine = arguments[arguments.length-1];//最后一个参数为类定义 if (!aDefine)//没有参数就返回 { return; } var aBase = arguments.length > 1?arguments[0]:object;//解析基类 function prototype_(){};//构造prototype的临时函数,用于挂接原型链 prototype_.prototype = aBase.prototype;//准备传递prototype var aPrototype = new prototype_();//建立类要用的prototype for (var member in aDefine)//复制类定义到当前类的prototype { if (member != "Create")//构造函数不用复制 { aPrototype[member] = aDefine[member]; } } //如果有构造函数 if (aDefine.Create) { var aType = aDefine.Create;//类型即为该构造函数 } else{//否则为默认构造函数。 aType = function(){ this.base.apply(this,arguments); } } aType.prototype = aPrototype; //设置类(构造函数)的prototype aType.Base = aBase; //设置类型关系 aType.prototype.Type = aType; //为本类对象扩展一个Type属性 return aType; //返回构造函数作为类 } //根类object定义 function object(){};//定义小写的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 Caller = object.prototype.base.caller; Caller && Caller.Base && Caller.Base.apply(this,arguments); } //应用效果 //默认派生自object基本类 var Person = Class({ Create:function(name,age){ this.base(); this.name = name; this.age = age; }, sayHello:function(){ alert("Hi,I am " + this.name + ", " + this.age + " years old."); } }); //Employee派生自Person var Employee = Class(Person,{ Create:function(name,age,salary){ this.base(name,age);//调用基类的构造函数 this.salary = salary; }, showMeTheMoney:function(){ alert(this.name + "'s salary is: $" + this.salary); } }); var wml = new Person("Wu Mingli",29); //wml.sayHello(); //var xyd = new Employee("Xu yedong",28,7500); //xyd.showMeTheMoney(); var lyp = new wml.Type("Lv yaping",25); lyp.sayHello();