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

时间:2023-03-09 15:37:01
JavaScript面向对象编程(9)高速构建继承关系之整合原型链

前面我们铺垫了非常多细节。是为了让大家更加明晰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());