码迷,mamicode.com
首页 > 移动开发 > 详细

call和apply的作用和区别

时间:2017-06-22 00:14:57      阅读:252      评论:0      收藏:0      [点我收藏+]

标签:数值   rip   arguments   转换   sub   log   false   nbsp   this   

 

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)

复杂案例:

function log(){
  var args=Array.prototype.slice.call(arguments);//将参数转为数组

  //slice(start,end(非必须) )方法可从已有的数组中返回选定的元素。

  //Javascript函数中的参数对象arguments是个对象,而不是数组。但它可以类似数组那样通过数字下表访问其中的元素,而且它也有length属性标识它的元素的个数。通常我们把它转换成数组用Array的slice函数,示例代码如下:function fn() { var arr = Array.prototype.slice.call(arguments,0);}

  //所以Array.prototype.slice.call(arguments)就是将参数转为数组然后返回数组

  console.log(args);//Array [ "hello", "world" ]
  args.unshift(‘(gykj)‘);//unshift(a,b,c)向数组的开头添加至少一个元素
  console.log(args);//Array [ "(gykj)", "hello", "world" ]
  console.log.apply(console,args);//(gykj) hello world 这里的apply可以将数组元素作为字符参数输出

  //由于参数个数不确定这里只能使用apply
}
log(‘hello‘,‘world‘)

call和apply的作用和区别

标签:数值   rip   arguments   转换   sub   log   false   nbsp   this   

原文地址:http://www.cnblogs.com/webwangjie/p/7062067.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!