標籤:
//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);
201506021403_《JavaScript完美甘露模型代碼》