Javascript call()、apply()和bind()的区别

  call()、apply()和bind()三个方法都用于在特定的作用域中调用函数,也就是设置函数体内this的值。那么这三个方法有什么区别呢?

一、call()

  语法:call([thisObj[,arg1[, arg2[, [,.argN]]]]])

    参数 thisObj 可选项。将被用作当前对象的对象。 arg1, arg2, , argN 可选项。将被传递方法参数序列。  

  说明:call 方法可以用来代替另一个对象调用一个方法。call 方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。 

  例子:

var name = "niu",age=45;

var obj1 = {
	name:"li",
	age:24
}
var obj2 = {
	name:"na",
	age:55
}
function outPut(){
	return "name:"+this.name+";age:"+this.age;
}
console.log(outPut());
console.log(outPut.call(obj1));
console.log(outPut.call(obj2));

  结果:

  从这个例子可以看出,在该函数中,更改了this的指向。再看一个例子:

var obj1 = {
	name:"li",
	age:24
}
var obj2 = {
	name:"na",
	age:55
}
function outPut(math, eng){
	return this.name+":Math:"+math+",English:"+eng;
}
console.log(outPut.call(obj1,67,98));
console.log(outPut.call(obj2,45,78));

  这次加入了参数,参数可以有多个。

  结果:

  

二、apply()

  语法:apply([thisObj[,argArray]]) 

  说明:如果 argArray 不是一个有效的数组或者不是 arguments 对象,那么将导致一个 TypeError。      

     如果没有提供 argArray 和 thisObj 任何一个参数,那么 Global 对象将被用作 thisObj, 并且无法被传递任何参数。

  例子:

var obj1 = {
	name:"li",
	age:24
}
var obj2 = {
	name:"na",
	age:55
}
function outPut(math, eng){
	return this.name+":Math:"+math+",English:"+eng;
}
console.log(outPut.apply(obj1,[67,98]));
console.log(outPut.apply(obj2,[45,78]));

  结果同上一个例子相同。

 *call()与apply()的区别就是接收参数的方式不同。call()方法的第一个参数是this值,而其余参数都直接传递给函数,也就是说,传递给函数的参数必须逐个列举出来。

  而apply()方法的第二个参数就是参数数组,可以是Array的实例,也可以是arguments对象。

三、bind()

  bind() 方法与 apply 和 call 很相似,也是可以改变函数体内 this 的指向。

  语法:function.bind(thisArg[,arg1[,arg2[,argN]]])

  参数:function:必选。一个函数对象。

     thisArg:必选。 this 关键字可在新函数中引用的对象。

     arg1[,arg2[,argN]]]:可选。要传递到新函数的参数的列表。

  例子:

var obj1 = {
	name:"li",
	age:24
}
var obj2 = {
	name:"na",
	age:55
}
function outPut(math, eng){
	return this.name+":Math:"+math+",English:"+eng;
}
console.log(outPut.bind(obj1)(67,98));
console.log(outPut.bind(obj2)(45,78));

  bind()方法可以返回与 function 函数相同的新函数,然后给逐个新函数传入参数进行调用。

posted @ 2016-07-25 14:18  一个悬浮在空中的胖子  阅读(205)  评论(0编辑  收藏  举报