JavaScript面向对象编程(9)快速构建继承关系之整合原型链

释放双眼,带上耳机,听听看~!

前面我们铺垫了很多细节,是为了让大家更加明晰prototype的使用细节;

现在可以将前面的知识整合起来,写一个函数用于快速构建基于原型链的继承关系了:


1
2
3
4
5
6
7
8
1function extend(Child, Parent) {
2   var F = function(){};
3   F.prototype = Parent.prototype;
4   Child.prototype = new F();
5   Child.prototype.constructor = Child;
6   Child.uber = Parent.prototype;
7}
8

1
2
1  使用起来也特别简单:
2

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
1function Shape(){}
2// augment prototype
3Shape.prototype.name = 'shape';
4Shape.prototype.toString = function(){
5   var result = [];
6   if (this.constructor.uber) {
7       result[result.length] = this.constructor.uber.toString();//super.toString()
8   }
9   result[result.length] = this.name;
10  return result.join(', ');
11};
12function TwoDShape(){}
13//先继承,再增强
14extend(TwoDShape,Shape);
15
16TwoDShape.prototype.name = '2D shape';
17
18function Triangle(side, height) {
19  this.side = side;
20  this.height = height;
21}
22
23extend(Triangle,TwoDShape);
24Triangle.prototype.name = 'Triangle';
25//使用继承而来的toString方法
26alert(new Triangle(10,5).toString());
27

给TA打赏
共{{data.count}}人
人已打赏
安全技术

RSA加密算法

2021-8-18 16:36:11

安全技术

C++ 高性能服务器网络框架设计细节

2022-1-11 12:36:11

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索