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

js call和apply方法

call()方法
call(obj,arg1,arg2...);
call()方法第一个参数是用作this的对象,其他参数直接传递给对象函数本身

例如:


function Cat(cColor){
   this.color=cColor;
   this.showColor=function(){
      alert(this.color); 
   }
}

function TomCat(cColor){
    Cat.call(this,cColor);
}
 var tom=new TomCat("black");
  tom.showColor();


applay()方法
applay(obj,Array)第一个参数也是用作this的对象,第二个参数为数组对象
例如

function Cat(cColor){
   this.color=cColor;
   this.showColor=function(){
      alert(this.color); 
   }
}

function TomCat(cColor){
    Cat.apply(this,new Array(cColor));
}
 var tom=new TomCat("black");
  tom.showColor();


也可把tomCat对象的arguments对象作为第二参数传递,如下
function Cat(cColor){
   this.color=cColor;
   this.showColor=function(){
      alert(this.color); 
   }
}

function TomCat(cColor){
    Cat.apply(this,arguments);
}
 var tom=new TomCat("black");
  tom.showColor();

1 楼 chunchong 2011-10-18  
貌似有点不大对
方法第一个参数是用作this的对象?????
2 楼 xixian 2011-10-18  
chunchong 写道
貌似有点不大对
方法第一个参数是用作this的对象?????


个人理解就是子类的对象

可参考w3school资料
http://www.w3school.com.cn/js/pro_js_inheritance_implementing.asp