声明父类与子类的示例:
/**
* Created by Administrator on 2015/12/23.
*/
//声明Rectangle类
function Rectangle(w, h) {
this.width = w;
this.height = h;
}
Rectangle.prototype.area = function () {
return this.width * this.height;
}
//父类定义了toString()方法+
Rectangle.prototype.toString = function(){
return "[width:" + this.width +",height:"+this.height+"]";
}
//2.1 声明PositionedRectangle子类
function PositionedRectangle(x,y,w,h){
//通过调用call()或apply()来调用Rectangle的构造方法。
Rectangle.call(this,w,h);
this.x=x;
this.y=y;
}
//2.2 如果我们需要使PositionedRectangle继承Rectangle,那么必需显式的创建PositionedRectangle的prototype属性。
PositionedRectangle.prototype=new Rectangle();
//2.3 删除不需要属性
//delete PositionedRectangle.prototype.width;
//delete PositionedRectangle.prototype.height;
//2.4 然后定义PositionedRectangle的构造函数为PositionedRectangle;
PositionedRectangle.prototype.constructor=PositionedRectangle;
//2.5 定义PositionedRectangle的函数
PositionedRectangle.prototype.contains=function(x,y){
return (x>this.x && x<this.x+this.width &&y>this.y && y<this.y+this.height);
}
PositionedRectangle.prototype.toString = function(){
return "("+this.x +","+this.y+")"+Rectangle.prototype.toString.apply(this);
}
// 3.1
function ZPositionedRectangle(z,x,y,width,height){
this.z =z;
//调用PositionedRectangle的构造方法,相当于继承于PositionedRectangle类。
PositionedRectangle.call(this,x,y,width,height);
}
ZPositionedRectangle.prototype = new PositionedRectangle();
ZPositionedRectangle.prototype.constructor=ZPositionedRectangle;
ZPositionedRectangle.prototype.toString = function(){
return "z:"+this.z+" "+PositionedRectangle.prototype.toString.apply(this);
}
//运行
//var r = new Rectangle(4,3);
var r = new PositionedRectangle(23,44,4,3);
console.log("area:"+r.area());
console.log("rectangle:"+ r.toString());
var r = new ZPositionedRectangle(2,23,44,4,3);
console.log("z rectangle:"+ r.toString());
for(prop in r){
console.log(prop+":"+ r.hasOwnProperty(prop));
}
r.pi=4;
console.log(r.pi);
d
本文展示了如何在JavaScript中实现类的继承,包括构造函数的使用和属性的继承。通过创建子类来扩展父类的功能,并定义特定的行为,如包含方法和重写父类的方法。

155

被折叠的 条评论
为什么被折叠?



