call和 apply的用法与区别

用法:都是修改this的指向

   function Obj(){
      this.name="sjz";
      this.getName=function(){
         console.log(this.name);
      }
   }
   var _obj={
      name:'aha'
   }
   var obj=new Obj();
   obj.getName();//输出sjz
   obj.getName.call(_obj);//输出aha
   obj.getName.apply(_obj);//输出aha

区别:传参的方式不同

   function Obj(name,age,num){
      this.name=name;
      this.age=age;
      this.num=num;
      this.show=function(a,b,c){          
         console.log(this.name+a);
         console.log(this.age+b);
         console.log(this.num+c);
      }
   }
   var _obj={
      name:'aha',age:'18',num:'33'
   }
   var obj=new Obj('sjz','22','15');
   obj.show(999,888,777);//输出sjz999,22888,15777
   obj.show.call(_obj,1,2,3);//输出aha1,182,333
   obj.show.apply(_obj,[1,2,3]);//输出aha1,182,333

 

posted @ 2020-03-20 23:55  sjzhen  阅读(110)  评论(0编辑  收藏  举报