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
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5
<title>原型鏈方式</title>
6
<script type="text/javascript">
7
/*
8
* 項目: book -> Javascript高級程序設計.pdf -> 第四章 -> 4.2.1 繼承的方式
9
* 說明:使用prototype屬性
10
* 練習者: Alex刺客
11
* 日期: 2009-12-13
12
*/
13
14
/*
15
原型鏈方式
16
原型鏈的神奇之處在于突出顯示的代碼,這里把ClassB的prototype屬性設置成ClassA的實例。
17
這很有意義,因為想要ClassA的所有屬性和方法。所以把ClassB的全部屬性設置成ClassA的實例。
18
因為這種繼承方式使用了prototype屬性,所以instanceof運算符可以正確運行。
19
*/
20
function ClassA () {}
21
22
ClassA.prototype.color = 'red';
23
ClassA.prototype.sayColor = function () {
24
alert(this.color);
25
}
26
27
function ClassB () {}
28
ClassB.prototype = new ClassA();
29
//添加新方法
30
ClassB.prototype.name = "ClassB";
31
ClassB.prototype.sayName = function () {
32
alert(this.name);
33
}
34
35
/*
36
混合方式 對象冒充+原型鏈
37
跟建造類一樣的問題也出現在繼承當中,所以也就產生了這種方式。
38
用對象冒充繼承構造函數,用原型鏈繼承prototype對象的方法。
39
*/
40
41
function ClassD ( sColor) {
42
this.color = sColor;
43
if(typeof ClassD._initMethod == "undefined") {
44
ClassD.prototype.sayColor = function () {
45
alert(this.color);
46
}
47
alert('ClassD我只生成一次!');
48
ClassD._initMethod = true;
49
}
50
}
51
var cd = new ClassD();
52
function ClassE (sColor, sName) {
53
ClassD.call(this,sColor);
54
this.name = sName;
55
if(typeof ClassE._initMethod == "undefined") {
56
ClassE.prototype.sayName =function () {
57
alert(this.name);
58
}
59
alert('ClassE我只生成一次!');
60
ClassE._initMethod = true;
61
}
62
}
63
ClassE.prototype = new ClassD();
64
/*
65
繼承機制不能采用動態化的原因是,prototype對象的唯一性。如果放入 if 區域
66
在代碼運行前,對象已被實例化了,并與原始的prototype對象聯系在一起。雖然用極
67
晚綁定可使對原型對象的修改正確地返映出來,但是替換prototype對象卻不會對該對象
68
產生任何影響。只有未來的對象實例才會反映出這種改變,這就使第一個實例變得不正確。
69
70
*/
71
72
var ce1 = new ClassE("red","blueBoy");
73
var ce2 = new ClassE("blue","redBoy");
74
ce1.sayColor();
75
ce1.sayName();
76
ce2.sayColor();
77
ce2.sayName();
78
79
80
</script>
81
</head>
82
<body>
83
</body>
84
</html>

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

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84
