日期:2014-05-16  浏览次数:20376 次

js学习笔记9
29.P190 超类与子类

function Rectangle(w,h){
this.width=w;
this.height=h;
this.PI=3.14159;
this.add=function(){return this.width + this.height;}//属性方法
}
Rectangle.prototype.area=function(){ //向Rectangle该对象添加一个方法
return this.width * this.height;
}
Rectangle.Max=function(a,b){ //Rectangle的Max属性方法定义为全局
if(a>b) return a;
else return b;
}
function PositionedRectangle(x,y,w,h){
this.PI=1;
Rectangle.call(this,w,h);//调用Rectangle的构造方法,PositionedRectangle这个对象中和Rectangle属性名字一致,会被父类的属性值给覆盖,也就是子类继承了父类的所有的属性。
alert(this.add());//能把Rectangle对象中的add()返回的值得到。
alert(this.area());//要想调用父类的原型对象,必须把父类的实例对象赋值给子类的原型对象。也就是PositionedRectangle.prototype = new Rectangle();
this.x=x;
this.y=y;
}
PositionedRectangle.prototype = new Rectangle();       //PositionedRectangle继承Rectangle原型对象的方法。
//alert(PositionedRectangle.prototype.area());
//PositionedRectangle.prototype.constructor=PositionedRectangle;//设置原型等于向的constructor的属性
var p=new PositionedRectangle(10,10,10,10);
alert(p.width);    // return  10  
alert(p.area());                           //return 100 调用父类的原型方法
alert(p instanceof PositionedRectangle);
alert(p instanceof Rectangle);        //return true ;PositionedRectangle.prototype = new Rectangle(); p的原型对象继承了Rectangle
alert(p instanceof Object);           //return true 所有的对象都是继承Object