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
* 練習者: Alex刺客
10
* 日期: 2009-12-13
11
*/
12
13
/*
14
1.對象冒充
15
*/
16
//ClassA類
17
function ClassA (sColor) {
18
this.color = sColor;
19
this.sayColor = function () {
20
alert(this.color);
21
}
22
}
23
24
//ClassB類
25
function ClassB(sColor,sName){
26
//當前對象的屬性是ClassA函數的指針
27
this.newMethod = ClassA;
28
//把參數傳遞給它
29
this.newMethod(sColor);
30
//刪除當前對象的ClassA函數的指針
31
delete this.newMethod;
32
33
//新增屬性和方法
34
this.name = sName;
35
this.sayName = function () {
36
alert(this.name);
37
}
38
}
39
40
//var cb = new ClassB("blue!","Redboy");
41
//cb.sayColor();
42
//cb.sayName();
43
44
/*
45
call()方法
46
call()方法與對象冒充方法最相似。它的第一個參數用作this的對象。
47
其他參數都直接傳遞給函數自身。
48
*/
49
//ClassC類
50
function ClassC(sColor,sName){
51
//this.newMethod = ClassA;
52
//this.newMethod(sColor);
53
//delete this.newMethod;
54
ClassA.call(this,sColor); //以上三行代碼由這行替代
55
56
//新增屬性和方法
57
this.name = sName;
58
this.sayName = function () {
59
alert(this.name);
60
}
61
}
62
63
//var cc = new ClassC("blue","c");
64
//cc.sayColor();
65
//cc.sayName();
66
67
/*
68
apply()方法
69
apply()方法有兩個參數,跟call()方法相似,只是第二個參數變成了數組。
70
*/
71
//ClassD類
72
function ClassD(sColor,sName){
73
//this.newMethod = ClassA;
74
//this.newMethod(sColor);
75
//delete this.newMethod;
76
ClassA.apply(this,new Array(sColor)); //以上三行代碼由這行替代
77
78
//新增屬性和方法
79
this.name = sName;
80
this.sayName = function () {
81
alert(this.name);
82
}
83
}
84
85
//var dt = new ClassD("red","blueBoy");
86
//dt.sayColor();
87
//dt.sayName();
88
89
</script>
90
</head>
91
<body>
92
</body>
93
</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

85

86

87

88

89

90

91

92

93
