我在找適用於各種主流瀏覽器的 XML 開發方式時,看到了一個有趣的 JavaScript 物件類別繼承寫法。
先來看看原始程式 (已重新改寫) :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
| TheParent = function () {
this.att1 = 'TEST';
this.att2 = 123;
this.method1 = function (msg) {
alert('TheParent::method1 - ' + msg);
}
this.method3 = function (msg) {
alert('TheParent::method3 - ' + msg);
}
}
TheChild = function () {
this.method2 = function (msg) {
return alert('TheChild::method2 - ' + msg);
}
// Override Method
this.method3 = function (msg) {
alert('TheChild::method3 - ' + msg);
}
}
TheChild.prototype = new TheParent();
var oTest = new TheChild();
oTest.method1(oTest.att1);
oTest.method2(oTest.att2);
oTest.method3(oTest.att2);
oTest.att1 = 'TEST AGAIN';
oTest.att2 = 456;
oTest.method1(oTest.att1);
oTest.method2(oTest.att2);
oTest.method3(oTest.att2);
|
重點就在於透過 prototype 屬性,把寫好的 function 物件類別繼承下來。
這樣的技巧就可以延伸出很多有趣的應用,像是 ECMAUnit 這個 JavaScript 的單元測試框架。
補充:既然可以 Inheritance (繼承) ,我也測試了一下 Override Method (覆寫函式) 。如上例所示,我在親類別和子類別各加入了一個 method3 ,沒有意外地,瀏覽器正確地執行了這個範例。