【笔记】uber--子对象访问父对象的方式

读书笔记《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都会被调用。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值