首页 > 编程语言 > 详细

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

时间:2014-12-24 00:04:16      阅读:277      评论:0      收藏:0      [点我收藏+]

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

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

function extend(Child, Parent) {
	var F = function(){};
	F.prototype = Parent.prototype;
	Child.prototype = new F();
	Child.prototype.constructor = Child;
	Child.uber = Parent.prototype;
}

使用起来也特别简单:

function Shape(){}
// augment prototype
Shape.prototype.name = 'shape';
Shape.prototype.toString = function(){
	var result = [];
	if (this.constructor.uber) {
		result[result.length] = this.constructor.uber.toString();//super.toString()
	}
	result[result.length] = this.name;
	return result.join(', ');
};
function TwoDShape(){}
//先继承,再增强
extend(TwoDShape,Shape);

TwoDShape.prototype.name = '2D shape';

function Triangle(side, height) {
	this.side = side;
	this.height = height;
}

extend(Triangle,TwoDShape);
Triangle.prototype.name = 'Triangle';
//使用继承而来的toString方法
alert(new Triangle(10,5).toString());


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

原文:http://blog.csdn.net/zhengwei223/article/details/42111681

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!