javascript中调用被覆盖的方法

本文介绍了JavaScript中通过构造函数实现继承的过程,并演示了如何在子类中重写父类的方法,同时保持父类方法的功能。
先定义一个父类的构造函数:
function Rectangle(w,h){
this.width = w; //代表矩形的宽
this.height= h; //代表矩形的高
}
Rectangle.prototype.area=function(){//此定义是构造函数原型对象的一个属性,它代表面积
return this.width * this.height;
}
Rectangle.prototype.toString=function(){//定义一个toString的原型方法
return "["+this.width+","+this.height+"]";
}

定义一个子类的构造函数来继承父类:javascript继承的具体介绍[url]http://han2000lei.iteye.com/blog/323506[/url]

function PositionedRectangle(x,y,w,h){
Rectangle.call(this,w,h); //使用函数的call()方法,以便初始化父类构造函数中的属性
this.x = x;
this.y = y;
}
PositionedRectangle.prototype = new Rectangle();
delete PositionedRectangle.prototype.width;
delete PositionedRectangle.prototype.height;
PositionedRectangle.prototype.constructor = PositionedRectangle;
PositionedRectangle.prototype.toString =function(){//重写父类中的toString方法
return "["+this.x+","+this.y+"]";
}

我们创建子类的一个实例,并调用子类的toString()方法
var pr = new PositionedRedtangle(2,2,8,3);
pr.toString();

上面代码不用解释了,子类调用自己的toString()就是执行的子类下面的toString()方法。我们在进行方法重写时,主要是为了扩展功能,而不是要完全覆盖父类的方法,那么我们如何才能调用父类中的这个方法呢?下面代码 :
PositionedRectangle.prototype.toString=function(){
return "("+this.x+","+this.y+")"+Rectangle.prototype.toString.apply(this);
}

这样,利用apply()方法,从而调用到了父类的toString()方法。具体的apply()方法的作用参考我的文档[url]http://han2000lei.iteye.com/blog/324680[/url]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值