javascript實現物件導向時,並沒有類似於java、c++的嚴格的類階層。所以想實現繼承,也不能通過extend等方式實現。不過javascript提供的原型鏈表機制可以很好的完成這一工作,實現繼承機制。
繼承的思想寬鬆點說就是子類繼承父類的屬性和方法,並且隱藏父類的同名屬性或方法。在javascript中實現該機制並不難,只不過比較粗糙一點,看下面的例子。
1: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2: <html xmlns="http://www.w3.org/1999/xhtml">
3: <head>
4: <title>javascript子類化</title>
5: <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
6: <meta name="generator" content="Ntcsoft" />
7: <meta name="author" content="MrZhou" />
8: <meta name="keywords" content="" />
9: <meta name="description" content="" />
10: </head>
11:
12: <body>
13:
14: <script type="text/javascript">
15: //父類建構函式
16: function fa (){
17: var privateFs = "private father String";//私人成員
18:
19: this.getPrivateFs = function(){ //私人成員的get方法
20: return privateFs;
21: }
22: this.setPrivateFs = function( str ){//私人成員的set方法
23: privateFs = str;
24: }
25:
26: this.fs = 'father string';
27: this.ff=function(){
28: alert('father function');
29: }
30: }
31: //子類建構函式
32: function son(){
33: this.ss = 'son string';
34: this.sf = function(){
35: alert('son function');
36: }
37: }
38: //實現子類繼承父類,這裡實際上是讓建構函式son的原型對象指向fa函數的執行個體,這樣,son的prototype屬性就擁有了fa執行個體對象的所有屬性和方法,
而son的執行個體會同時擁有son和fa類的this指定的屬性和方法。
39: son.prototype = new fa();
40:
41: //通過子類建構函式產生執行個體對象。
42: var newBoy = new son();
43: //alert(newBoy.fs);//father string
44: //alert(newBoy.ss)//son string
45:
46: /*(這時候彈出的是fa函數的內容而不是son函數的內容)
47: 不過這樣做有幾個缺點:這樣做實際上是幹掉了son的prototype,隨之也幹掉了son的prototype對象的constructor屬性。不過我們也有解決辦法。*/
48: //alert(son.prototype.constructor)
49:
50: //son.prototype.constructor = son;
51: //alert(son.prototype.constructor);
52:
53: //通過get,set方法讀寫父類的私人屬性
54: newBoy.setPrivateFs("123");
55: alert(newBoy.getPrivateFs());
56: </script>
57:
58: </body>
59: </html>