call和apply的区别、作用

call和apply用来调用函数,并用指定对象(第一个参数)替换函数的 this 值,同时用指定数组替换函数的参数。注:也可以不指定参数,此时只是单纯的调用函数,如:fun.call()

语法:

  fun.call(thisobj,arg1,arg2) ;当后面参数个数确定时用call,参数之间用逗号连接

  fun.apply(thisobj,[arg1,arg2]);当后面参数个数不确定时用apply,参数通过数组形式输入

call和apply的作用:

  改变this的指向,第一个参数为你要传入的对象,传入后函数的this就指向了这个对象,后面的参数为你为函数传递的参数值

简单案例:

var str='js';
function fo(){
  var str='jq';
  console.log(this.str);//此时this指向window
  console.log(this===window);
  console.log(this===obj);
  //输出js,true,false
}
fo();
var obj={
  str:'html'
};
fo.call(obj)//输出html,false,true,这就证明了call将fo的this指向改为了obj;
var ob={
  str:'css',
}
var get=function(){
  console.log(str);//js 此时读取的是全局变量的值
  console.log(this.str);//css 此时this指向了ob,返回的就是ob.str
}
get.call(ob)

猜你喜欢

转载自blog.csdn.net/qq_36195950/article/details/81449524