VS 2008
本文介紹如何使用Microsoft Asp.Net Ajax Library編寫名稱空間、類、繼承、介面等OO代碼
1. 準備
建立一個"Ajax client library"指令檔:Person.js
在default.aspx頁面上加入ScirptManager控制項:
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Scripts>
<asp:ScriptReference Path="~/Person.js" />
</Scripts>
</asp:ScriptManager>
2. namespace
在Person.js中加入代碼註冊我們定義的名稱空間:
Type.registerNamespace("Tristan");
3. class
現在我們在Person.js中定義一個Person類:
Tristan.Person = function(name) {
this._name = name;
}
Tristan.Person.prototype = {
get_name : function() {
return this._name;
},
set_name : function(name) {
this._name = name;
},
sayHello : function() {
alert('I am a person, my name is ' + this._name);
}
}
Tristan.Person.registerClass("Tristan.Person");
編寫測試代碼:var p = new Tristan.Person('guozhijian');
p.sayHello();
運行:彈出提示框 "I am a person, my name is guozhijian"
4. inheritance
現在編寫一個Student類繼承自Person類:
Tristan.Student = function(name) {
Tristan.Student.initializeBase(this, [name]);
}
Tristan.Student.registerClass("Tristan.Student", Tristan.Person);
兩個步驟實現繼承:
1) 子類建構函式中調用 initializeBase方法,第一個param為關鍵字this,第二個參數為建構函式參數組成的Array
2) 類代碼的末尾調用 registerClass方法,標明父類
編寫測試代碼:var s = new Tristan.Student("zhenglanzhen");
s.sayHello();
運行:彈出提示框 "I am a person, my name is zhenglanzhen"
現在我要override sayHello方法:Tristan.Student.prototype = {
sayHello : function() {
alert('I am a student, my name is ' + this._name);
}
}
運行:彈出提示框 "I am a student, my name is zhenglanzhen"
改一下,我的sayHello方法要先調用一下父類的sayHello方法,然後再接著子類自己的邏輯,那麼:
Tristan.Student.prototype = {
sayHello : function() {
Tristan.Student.callBaseMethod(this, 'sayHello');
alert('actually I am a student');
}
}
實現步驟:調用callBaseMethod方法,第一參數:this關鍵字, 第二個參數:要調用的父類的方法名,第三個參數:可選,如果父類的這個方法有參數,則為參數列表組成的Array
運行:彈出提示框 "I am a person, my name is zhenglanzhen"
彈出提示框 "actually I am a student"
5. interface
現在要讓Student有行走的行為,定義一個介面 IWalkable:Tristan.IWalkable = function() {
throw Error.notImplemented();
}
Tristan.IWalkable.prototype = {
walk : function() {
throw Error.notImplemented();
}
}
Tristan.IWalkable.registerInterface("Tristan.IWalkable");
實現步驟:
1. 方法中都拋異常,避免介面被執行個體化
2. 調用registerInterface方法
現在要讓Student類實現IWalkable介面,對Student類做如下改動:Tristan.Student.registerClass("Tristan.Student", Tristan.Person, Tristan.IWalkable);
標明Student類實現Tristan.IWalkable介面,如果要實現多個介面,那麼繼續往後加參數
編寫測試代碼:var s = new Tristan.Student("zhenglanzhen");
s.walk();
運行:報錯了!啊,walk方法還沒有實現
對Student做如下改動:Tristan.Student.prototype = {
sayHello : function() {
Tristan.Student.callBaseMethod(this, 'sayHello');
alert('actually I am a student');
},
walk : function() {
alert('I am walking');
}
}
再次運行測試代碼,彈出提示框 "I am walking"