javascript中多继承

js中的继承
function classA(sColor)
{
   this.color=sColor;
   this.sayColor=function()
   {
      alert(this.color);
   };
}
1、对象冒充
function classB(sColor)
{
   this.newMethod=classA;
   this.newMethod(sColor);
   delete this.newMethod;
}
2、call()方法
function classB(sColor)
{
   //this.newMethod=classA;
   //this.newMethod(sColor);
   //delete this.newMethod;
   classA.call(this,sColor);
}

//////////other
function sayColor(sPrefix,sSuffix)
{
   alert(sPrefix+this.color+sSuffix);
};
var obj=new Object();
obj.color="red";
sayColor.call(obj,"The color is",",a very nice color indeed.");
3、apply()方法
function classB(sColor)
{
   //this.newMethod=classA;
   //this.newMethod(sColor);
   //delete this.newMethod;
   classA.apply(this,new Array(sColor));
}

function classB(sColor)
{
   //classA.apply(this,new Array(sColor));
   classA.apply(this,arguments);
}

4、原型链
function classA(){}
classA.prototype.color="red";
classA.prototype.sayColor=function()
{
   alert(this.color);
};
function classB(){}
classB.prototype=new classA();
`

//////////other
function sayColor(sPrefix,sSuffix)
{
   alert(sPrefix+this.color+sSuffix);
};
var obj=new Object();
obj.color="red";
sayColor.apply(obj,new Array("The color is",",a very nice color indeed."));
5、采用冬天原型方法时多继承
function Polygon(iSides)
{
   this.sides=iSides;
   if(typeof Polygon._initialized=="undefined")
   {
      Polygon.prototype.getArea=function(){return 0;};
      Polygon._initialized=true;
   }
}

function Triangle(iBase,iHeight)
{
   Polygon.call(this,3);
   this.base=iBase;
   this.height=iHeight;
   
   if(typeof Triangle._initialized=="undefined")
   {
      //Triangle.prototype=new Polygon();
      //注意上面这句话不能放在类内部,否则会影响基类
      Triangle.prototype.getArea=function()
      {
         return 0.5 * this.base * this.height;
      }
      Triangle._initialized=true;
   }
}

//注意下面这句话只能放在继承类多外面,否则会影响基类
Triangle.prototype=new Polygon();

posted @ 2010-07-09 17:52  星释天狼  阅读(328)  评论(0)    收藏  举报