//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);