call与apply

function show(){

  alert(this);

}

//一般调用函数

show();//window

 

按理说 函数调用是这样的,我们一般会省略掉call(),或者apply

 

show.call();//window

show.call(123);//123

show.call('abc');//abc

从上面的运行结果可以看出来,call()里面的第一个参数可以改变this指向

如果函数有参数怎么办呢?

function show(a,b){

  alert('this是'+this+,+'a是'+a+'b是'+b);

}

show(3,5);//this是window,a是3,b是5

show.call('div',3,5);//this是div,a是3,b是5

show.apply('div',[3,5]);//this是div,a是3,b是5  

call()和apply() 不相同的地方是call(this,a,b,c,...);而apply(this,[a,b,c,...]);把参数放进一个数组里

 

posted @ 2017-01-09 14:32  daidai201  阅读(120)  评论(0编辑  收藏  举报