上一讲我们提出一个很好的思路,将一个类的可复用部分全部定义在prototype中,这样子类继承的时候可以很方便地通过prototype来继承;
但是也带来一个问题就是子类在重写prototype中的属性时会改变所有实例的属性,这是因为父类和子类实例都共享同一个prototype;
怎么解决呢?思路就是利用一个中间函数,具体请看代码:
1
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 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>临时函数F</title>
6</head>
7
8<body>
9<script type="text/javascript">
10function Shape(){
11
12}
13Shape.prototype.name = 'shape';
14Shape.prototype.toString = function() {return this.name;};
15
16function TwoDShape(){
17
18}
19//用中间函数先继承基类
20var F = function(){}
21F.prototype=Shape.prototype;
22//子类继承中间函数
23TwoDShape.prototype = new F();
24TwoDShape.prototype.constructor = TwoDShape;
25
26//这是真正的重写
27TwoDShape.prototype.name = '2D shape';
28
29function Triangle(side, height) {
30 this.side = side;
31 this.height = height;
32 this.getArea = function(){return this.side * this.height / 2;};
33}
34var F = function(){}
35F.prototype=TwoDShape.prototype;
36Triangle.prototype = new F();
37
38Triangle.prototype.constructor = Triangle;
39//重写
40Triangle.prototype.name="Triangle";
41
42
43var my = new Triangle(5, 10);
44/*
45alert(my.getArea());
46alert(my.toString());//自己没有toString方法,继承而来
47alert(my.constructor);
48alert(my instanceof TwoDShape);//有继承的特性
49alert(my instanceof Shape);
50*/
51alert(my.name);
52var shape = new Shape();
53alert(shape.name);//正常了
54
55</script>
56</body>
57</html>
58
59