先定义一个父类的构造函数:
定义一个子类的构造函数来继承父类:javascript继承的具体介绍[url]http://han2000lei.iteye.com/blog/323506[/url]
我们创建子类的一个实例,并调用子类的toString()方法
上面代码不用解释了,子类调用自己的toString()就是执行的子类下面的toString()方法。我们在进行方法重写时,主要是为了扩展功能,而不是要完全覆盖父类的方法,那么我们如何才能调用父类中的这个方法呢?下面代码 :
这样,利用apply()方法,从而调用到了父类的toString()方法。具体的apply()方法的作用参考我的文档[url]http://han2000lei.iteye.com/blog/324680[/url]
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]