码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2014-12-24 00:05:47      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:javascript   面向对象编程   js   编程语言   

前面我们铺垫了很多细节,是为了让大家更加明晰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)快速构建继承关系之整合原型链

标签:javascript   面向对象编程   js   编程语言   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!