声明父类与子类的示例:
/** * 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