`
xixian
  • 浏览: 211045 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

js call和apply方法

    博客分类:
  • js
阅读更多

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();

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


个人理解就是子类的对象

可参考w3school资料
http://www.w3school.com.cn/js/pro_js_inheritance_implementing.asp
1 楼 chunchong 2011-10-18  
貌似有点不大对
方法第一个参数是用作this的对象?????

相关推荐

Global site tag (gtag.js) - Google Analytics