javascript類繼承模型

//語法甘露:
var object = //定義小寫的object 基本類,用於實現最基礎的方法等
{
isA: function(aType) //一個判斷類與類之間以及對象與類之間關系的基礎方法
{
var self = this;
32
while(self)
{
if (self == aType)
return true;
self = self.Type;
};
return false;
}
};
function Class(aBaseClass, aClassDefine) //創建類的函數,用於聲明類及繼承關系
{
function class_() //創建類的臨時函數殼
{
this.Type = aBaseClass; //我們給每一個類約定一個Type 屬性,引用其繼承的

for(var member in aClassDefine)
this[member] = aClassDefine[member]; //復制類的全部定義到當前創建
的類
};
class_.prototype = aBaseClass;
return new class_();
};
function New(aClass, aParams) //創建對象的函數,用於任意類的對象創建
{
function new_() //創建對象的臨時函數殼
{
this.Type = aClass; //我們也給每一個對象約定一個Type 屬性,據此可以訪問
到對象所屬的類
33
if (aClass.Create)
aClass.Create.apply(this, aParams); //我們約定所有類的構造函數都叫Crea
te,這和DELPHI 比較相似
};
new_.prototype = aClass;
return new new_();
};
//語法甘露的應用效果:
var Person = Class(object, //派生至object 基本類
{
Create: function(name, age)
{
this.name = name;
this.age = age;
},
SayHello: function()
{
alert("Hello, I'm " + this.name + ", " + this.age + " years old.");
}
});
var Employee = Class(Person, //派生至Person 類,是不是和一般對象語言很相似?
{
Create: function(name, age, salary)
{
Person.Create.call(this, name, age); //調用基類的構造函數
this.salary = salary;
},
ShowMeTheMoney: function()
34
{
alert(this.name + " $" + this.salary);
}
});
var BillGates = New(Person, ["Bill Gates", 53]);
var SteveJobs = New(Employee, ["Steve Jobs", 53, 1234]);
BillGates.SayHello();
SteveJobs.SayHello();
SteveJobs.ShowMeTheMoney();
var LittleBill = New(BillGates.Type, ["Little Bill", 6]); //根據BillGate 的類型創建
LittleBill
LittleBill.SayHello();
alert(BillGates.isA(Person)); //true
alert(BillGates.isA(Employee)); //false
alert(SteveJobs.isA(Person)); //true
alert(Person.isA(Employee)); //false
alert(Employee.isA(Person)); //true

 

本文出自“mayi-hetu”
 

You May Also Like