apply、call

来源:互联网 发布:如何修改sql数据库名称 编辑:程序博客网 时间:2024/05/18 14:45

apply、call

在js中,callapply都是为了改变某个函数运行时的上下文(context)而存在的,换句话说,就是为了改变函数体内部的this指向。
js的一大特点是,函数存在定义时上下文运行时上下文以及上下文是可以改变的这样的概念。

function fruits(){}fruits.prototype = {  color:'red',  say:function(){console.log('my color is '+this.color);}}var apple = new fruits;apple.say(); //'my color is red'

如果我们有一个对象banner = {color:'yellow'},我们不想重新定义say方法,那么我们可以通过call或者apply调用apple对象是say方法:

var banana = {color:'yellow'};apple.say.call(banana);//'my color is yellow'apple.say.apple(banana); //'my color is yellow'

所以可以看出,callapple是为了动态改变this而出现的,当一个对象没有某个方法(banana对象没有say方法),但是其他的对象有(apple对象有say方法),我们可以借助call或者apply调用其他对象的方法来操作。

apply、call的区别

对于apply、call二者而言,作用完全一样,只是接受参数的方式不太一样。

var func = function(arg1,arg2){}

可以通过如下方式来调用:

func.call(this,arg1,arg2);func.apply(this,[arg1,arg2]);

其中的this是你想指定的上下文,它可以是任何一个js对象,call需要把参数按顺序传递进去,而apply则是把参数放在数组里。

在js中,某个函数的参数数量是不固定的,因此要说适用条件的画,当你的参数是明确知道数量时用call;而不确定参数个人的时候用apply,然后把参数push进数组。
当参数数量不确定时,函数内部也可以通过arguments这个数组来遍历。

为了巩固加深记忆,下面列举一些常用方法:
1.数组之间的追加

var arr1 = [12,'foo',{name:'joe'},-2458];var arr2 = ['doe',555,100];Array.prototype.push.apply(arr1,arr2);//arr1的值为: [12,'foo',{name:'joe'},-2458,'doe',555,100]

2.获取数组中最大值和最小值

var numbers = [5,458,120];var maxNumbers = Math.max.apply(Math,numbers); //458maxNumbers = Math.max.call(Math,5,458,120); //458

number本身没有max方法,但Math有,我们可以借助callapply使用其方法。

3.验证是否是数组(前提是toString()方法没有被重写过)

function isArray(obj){  return Object.prototype.toString.call(obj) === '[object Array]';}

深入理解运用apply、call

定义一个log方法,让它可以代理console.log

function log(msg){  console.log(msg);}log(1); //1log(2); //2

上面的方法在当传入的参数个人不确定时,就无效了。这个时候就可以考虑使用apply

function log(){  console.log.apply(console,arguments);};log(1);//1log(1,2);//1 2
0 0