前几天看到js的对象和继承的两种实现总结了一下然后在这里记录下来:
1
<html>
2
<head>
3
<script language="javascript" type="text/javascript">
4
function BaseClass(name)
5
{
6
this.TypeName = name;
7
this.writeBaseName = function()
8
{
9
document.write("Base Name: ");
10
document.write(this.TypeName);
11
document.write("<br />");
12
}
13
}
14
15
function DeriveClass(name)
16
{
17
var base = new BaseClass("Cat");
18
base.Name = name;
19
base.writeDeriveName = function()
20
{
21
document.write("Derived Name: ");
22
document.write(base.Name);
23
}
24
return base;
25
}
26
27
var base = new DeriveClass("tom");
28
base.writeBaseName();
29
base.writeDeriveName();
30
</script>
31
</head>
32
<body>
33
</body>
34
</html>
35
这种就是相当于平常的组合,因为js本身并不支持继承和接口,所以这种组合的实现是比较通用的方法。另外就是调用call 方法:示例如下:
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

1
<html>
2
<head>
3
<script language="javascript">
4
function ClassA(prop)
5
{
6
this.prop = prop;
7
this.fun2 = function()
8
{
9
document.writeln(this.prop);
10
document.writeln("ok in class A");
11
document.writeln("<br />");
12
}
13
}
14
15
var a = new ClassA("a");
16
a.fun2();
17
18
function ClassB(prop,name)
19
{
20
ClassA.call(this,prop);
21
this.name = name;
22
this.fun2 = function()
23
{
24
document.writeln(this.prop);
25
alert("ok in class B");
26
document.writeln("<br />");
27
}
28
}
29
var b = new ClassB("B","b");
30
b.fun2();
31
</script>
32
</head>
33
</html>
34

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
