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
* 項(xiàng)目: book -> Javascript高級(jí)程序設(shè)計(jì).pdf -> 第四章 -> 4.2.1 繼承的方式
9
* 說(shuō)明:使用prototype屬性
10
* 練習(xí)者: Alex刺客
11
* 日期: 2009-12-13
12
*/
13
14
/*
15
原型鏈方式
16
原型鏈的神奇之處在于突出顯示的代碼,這里把ClassB的prototype屬性設(shè)置成ClassA的實(shí)例。
17
這很有意義,因?yàn)橄胍狢lassA的所有屬性和方法。所以把ClassB的全部屬性設(shè)置成ClassA的實(shí)例。
18
因?yàn)檫@種繼承方式使用了prototype屬性,所以instanceof運(yùn)算符可以正確運(yùn)行。
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
混合方式 對(duì)象冒充+原型鏈
37
跟建造類一樣的問(wèn)題也出現(xiàn)在繼承當(dāng)中,所以也就產(chǎn)生了這種方式。
38
用對(duì)象冒充繼承構(gòu)造函數(shù),用原型鏈繼承prototype對(duì)象的方法。
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
繼承機(jī)制不能采用動(dòng)態(tài)化的原因是,prototype對(duì)象的唯一性。如果放入 if 區(qū)域
66
在代碼運(yùn)行前,對(duì)象已被實(shí)例化了,并與原始的prototype對(duì)象聯(lián)系在一起。雖然用極
67
晚綁定可使對(duì)原型對(duì)象的修改正確地返映出來(lái),但是替換prototype對(duì)象卻不會(huì)對(duì)該對(duì)象
68
產(chǎn)生任何影響。只有未來(lái)的對(duì)象實(shí)例才會(huì)反映出這種改變,這就使第一個(gè)實(shí)例變得不正確。
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
