Javascriptのクラスとサブクラスの作成

2512 ワード

親と子の宣言の例:
/**
 * 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