读书笔记《javascript面向对象编程指南》
function Shape(){}
Shape.prototype.name = 'shape';
Shape.prototype.toString = function(){
var result = [];
if (this.constructor.uber) {
result[result.length] = this.constructor.uber.toString();
}
result[result.length] = this.name;
return result.join(', ');
};
function TwoDShape(){}
var F = function(){};
F.prototype = Shape.prototype;
TwoDShape.prototype = new F();
TwoDShape.prototype.constructor = TwoDShape;
TwoDShape.uber = Shape.prototype;
TwoDShape.prototype.name = '2d shape';
function Triangle(side,height){
this.side = side;
this.height = height;
}
var F = function(){}
F.prototype = TwoDShape.prototype;
Triangle.prototype = new F();
Triangle.prototype.constructor = Triangle;
Triangle.uber = TwoDShape.prototype;
Triangle.prototype.name = 'Triangle';
Triangle.prototype.getArea = function(){
return this.side*this.height/2;
}
var my = new Triangle(5, 10);
my.toString()
-->"shape, 2d shape, Triangle"
上面的代码中:
1、将uber属性设置成了指向其父级原型的引用
2、对toSting()方法进行了更新。
在这之前,toString()所做的仅仅是返回this.name的内容而已,现在新增了额外的任务,检查对象中是否存在this.constructor.uber属性。
如果存在,就先调用该属性的toString方法。
this.constructor.uber指向当前对象父级原型的引用。
因而,当调用Triangle实体的toString方法时,其原型链上所有的toString都会被调用。