在JavaScript中,call
、apply
和bind
是Function
对象自带的三个方法,这三个方法的主要做用是改变函数中的this
指向。javascript
call
、apply
、bind
方法的共同点和区别:apply
、 call
、bind
三者都是用来改变函数的this对象的指向的;apply
、 call
、bind
三者第一个参数都是this要指向的对象,也就是想指定的上下文(函数的每次调用都会拥有一个特殊值——本次调用的上下文(context)——这就是this
关键字的值。);apply
、 call
、bind
三者均可以利用后续参数传参;bind
是返回对应函数,便于稍后调用;apply
、call
则是当即调用 。html
1、calljava
call()
语法:面试
call([thisObj[,arg1[, arg2[, [,.argN]]]]])
定义:调用一个对象的一个方法,以另外一个对象替换当前对象。segmentfault
说明: call
方法能够用来代替另外一个对象调用一个方法。call
方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。数组
thisObj
的取值有如下4种状况:
(1) 不传,或者传null,undefined, 函数中的this指向window对象
(2) 传递另外一个函数的函数名,函数中的this指向这个函数的引用
(3) 传递字符串、数值或布尔类型等基础类型,函数中的this指向其对应的包装对象,如 String、Number、Boolean
(4) 传递一个对象,函数中的this指向这个对象app
function a(){ console.log(this); //输出函数a中的this对象 } function b(){} var c={name:"call"}; //定义对象c a.call(); //window a.call(null); //window a.call(undefined); //window a.call(1); //Number a.call(''); //String a.call(true); //Boolean a.call(b); //function b(){} a.call(c); //Object
若是你不理解上面的,不要紧,咱们再来看一个例子:dom
function class1(){ this.name=function(){ console.log("我是class1内的方法"); } } function class2(){ class1.call(this); //此行代码执行后,当前的this指向了class1(也能够说class2继承了class1) } var f=new class2(); f.name(); //调用的是class1内的方法,将class1的name方法交给class2使用
经常使用例子:
(1)函数
function eat(x,y){ console.log(x+y); } function drink(x,y){ console.log(x-y); } eat.call(drink,3,2); 输出:5
这个例子中的意思就是用 eat 来替换 drink,eat.call(drink,3,2) == eat(3,2) ,因此运行结果为:console.log(5);
注意:js 中的函数实际上是对象,函数名是对 Function 对象的引用。工具
(2)
function Animal(){ this.name="animal"; this.showName=function(){ console.log(this.name); } } function Dog(){ this.name="dog"; } var animal=new Animal(); var dog=new Dog(); animal.showName.call(dog); 输出:dog
在上面的代码中,咱们能够看到Dog里并无showName方法,那为何(this.name)的值是dog呢?
关键就在于最后一段代码(animal.showName.call(dog)),意思是把animal的方法放到dog上执行,也能够说,把animal 的showName()方法放到 dog上来执行,因此this.name 应该是 dog。
(3)继承
function Animal(name){ this.name=name; this.showName=function(){ console.log(this.name); } } function Dog(name){ Animal.call(this,name); } var dog=new Dog("Crazy dog"); dog.showName(); 输出:Crazy dog
Animal.call(this) 的意思就是使用 Animal对象代替this对象,那么Dog就能直接调用Animal的全部属性和方法。
2、apply()
语法:apply([thisObj[,argArray]])
定义:应用某一对象的一个方法,用另外一个对象替换当前对象。
说明:
若是 argArray 不是一个有效的数组或者不是 arguments 对象,那么将致使一个 TypeError。
若是没有提供 argArray 和 thisObj 任何一个参数,那么 Global 对象将被用做 thisObj, 而且没法被传递任何参数。
call 和 apply的区别
对于 apply、call 两者而言,做用彻底同样,只是接受参数的方式不太同样。
function class1(args1,args2){ this.name=function(){ console.log(args,args); } } function class2(){ var args1="1"; var args2="2"; class1.call(this,args1,args2); /*或*/ class1.apply(this,[args1,args2]); } var c=new class2(); c.name(); 输出:1 2
call
须要把参数按顺序传递进去,而 apply
则是把参数放在数组里。
既然二者功能同样,那该用哪一个呢?
在JavaScript 中,某个函数的参数数量是不固定的,所以要说适用条件的话,当你的参数是明确知道数量时用 call ;而不肯定的时候用 apply,而后把参数 push 进数组传递进去。当参数数量不肯定时,函数内部也能够经过 arguments 这个数组来遍历全部的参数。
3、bindbind
是在EcmaScript5中扩展的方法(IE6,7,8不支持)bind()
方法与 apply 和 call 很类似,也是能够改变函数体内 this
的指向。
MDN的解释是:bind()
方法会建立一个新函数,称为绑定函数,当调用这个绑定函数时,绑定函数会以建立它时传入 bind()
方法的第一个参数做为 this
,传入 bind()
方法的第二个以及之后的参数加上绑定函数运行时自己的参数按照顺序做为原函数的参数来调用原函数。
注意:bind
方法的返回值是函数
var bar=function(){ console.log(this.x); } var foo={ x:3 } bar(); bar.bind(foo)(); /*或*/ var func=bar.bind(foo); func(); 输出: undefined 3
1
2
3
4
5
6
7
8
9
10
11
|
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
|
可是若是咱们有一个对象banana= {color : "yellow"} ,咱们不想对它从新定义 say 方法,那么咱们能够经过 call 或 apply 用 apple 的 say 方法:
1
2
3
4
5
|
banana = {
color:
"yellow"
}
apple.say.call(banana);
//My color is yellow
apple.say.apply(banana);
//My color is yellow
|
因此,能够看出 call 和 apply 是为了动态改变 this 而出现的,当一个 object 没有某个方法(本栗子中banana没有say方法),可是其余的有(本栗子中apple有say方法),咱们能够借助call或apply用其它对象的方法来操做。
apply、call 的区别
对于 apply、call 两者而言,做用彻底同样,只是接受参数的方式不太同样。例如,有一个函数定义以下:
1
2
3
|
var
func =
function
(arg1, arg2) {
};
|
就能够经过以下方式来调用:
1
2
|
func.call(
this
, arg1, arg2);
func.apply(
this
, [arg1, arg2])
|
其中 this 是你想指定的上下文,他能够是任何一个 JavaScript 对象(JavaScript 中一切皆对象),call 须要把参数按顺序传递进去,而 apply 则是把参数放在数组里。
1
2
3
4
|
var
array1 = [12 ,
"foo"
, {name
"Joe"
} , -2458];
var
array2 = [
"Doe"
, 555 , 100];
Array.prototype.push.apply(array1, array2);
/* array1 值为 [12 , "foo" , {name "Joe"} , -2458 , "Doe" , 555 , 100] */
|
二、获取数组中的最大值和最小值
1
2
3
|
var
numbers = [5, 458 , 120 , -215 ];
var
maxInNumbers = Math.max.apply(Math, numbers),
//458
maxInNumbers = Math.max.call(Math,5, 458 , 120 , -215);
//458
|
number 自己没有 max 方法,可是 Math 有,咱们就能够借助 call 或者 apply 使用其方法。
三、验证是不是数组(前提是toString()方法没有被重写过)
1
2
3
|
functionisArray(obj){
return
Object.prototype.toString.call(obj) ===
'[object Array]'
;
}
|
四、类(伪)数组使用数组方法
1
|
var
domNodes = Array.prototype.slice.call(document.getElementsByTagName(
"*"
));
|
深刻理解运用apply、call
下面就【借用一道面试题】,来更深刻的去理解下 apply 和 call 。
定义一个 log 方法,让它能够代理 console.log 方法,常见的解决方法是:
1
2
3
4
5
|
function
log(msg) {
console.log(msg);
}
log(1);
//1
log(1,2);
//1
|
上面方法能够解决最基本的需求,可是当传入参数的个数是不肯定的时候,上面的方法就失效了,这个时候就能够考虑使用 apply 或者 call,注意这里传入多少个参数是不肯定的,因此使用apply是最好的,方法以下:
1
2
3
4
5
|
function
log(){
console.log.apply(console, arguments);
};
log(1);
//1
log(1,2);
//1 2
|
接下来的要求是给每个 log 消息添加一个"(app)"的前辍,好比:
1
|
log(
"hello world"
);
//(app)hello world
|
该怎么作比较优雅呢?这个时候须要想到arguments参数是个伪数组,经过 Array.prototype.slice.call 转化为标准数组,再使用数组方法unshift,像这样:
1
2
3
4
5
6
|
function
log(){
var
args = Array.prototype.slice.call(arguments);
args.unshift(
'(app)'
);
console.log.apply(console, args);
};
|
bind
说完了 apply 和 call ,再来讲说bind。bind() 方法与 apply 和 call 很类似,也是能够改变函数体内 this 的指向。
MDN的解释是:bind()方法会建立一个新函数,称为绑定函数,当调用这个绑定函数时,绑定函数会以建立它时传入 bind()方法的第一个参数做为 this,传入 bind() 方法的第二个以及之后的参数加上绑定函数运行时自己的参数按照顺序做为原函数的参数来调用原函数。
直接来看看具体如何使用,在常见的单体模式中,一般咱们会使用 _this , that , self 等保存 this ,这样咱们能够在改变了上下文以后继续引用到它。 像这样:
1
2
3
4
5
6
7
8
9
10
|
var
foo = {
bar : 1,
eventBind:
function
(){
var
_this =
this
;
$(
'.someClass'
).on(
'click'
,
function
(event) {
/* Act on the event */
console.log(_this.bar);
//1
});
}
}
|
因为 Javascript 特有的机制,上下文环境在 eventBind:function(){ } 过渡到 $('.someClass').on('click',function(event) { }) 发生了改变,上述使用变量保存 this 这些方式都是有用的,也没有什么问题。固然使用 bind() 能够更加优雅的解决这个问题:
1
2
3
4
5
6
7
8
9
|
var
foo = {
bar : 1,
eventBind:
function
(){
$(
'.someClass'
).on(
'click'
,
function
(event) {
/* Act on the event */
console.log(
this
.bar);
//1
}.bind(
this
));
}
}
|
在上述代码里,bind() 建立了一个函数,当这个click事件绑定在被调用的时候,它的 this 关键词会被设置成被传入的值(这里指调用bind()时传入的参数)。所以,这里咱们传入想要的上下文 this(其实就是 foo ),到 bind() 函数中。而后,当回调函数被执行的时候, this 便指向 foo 对象。再来一个简单的栗子:
1
2
3
4
5
6
7
8
9
|
var
bar =
function
(){
console.log(
this
.x);
}
var
foo = {
x:3
}
bar();
// undefined
var
func = bar.bind(foo);
func();
// 3
|
这里咱们建立了一个新的函数 func,当使用 bind() 建立一个绑定函数以后,它被执行的时候,它的 this 会被设置成 foo , 而不是像咱们调用 bar() 时的全局做用域。
有个有趣的问题,若是连续 bind() 两次,亦或者是连续 bind() 三次那么输出的值是什么呢?像这样:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
var
bar =
function
(){
console.log(
this
.x);
}
var
foo = {
x:3
}
var
sed = {
x:4
}
var
func = bar.bind(foo).bind(sed);
func();
//?
var
fiv = {
x:5
}
var
func = bar.bind(foo).bind(sed).bind(fiv);
func();
//?
|
答案是,两次都仍将输出 3 ,而非期待中的 4 和 5 。缘由是,在Javascript中,屡次 bind() 是无效的。更深层次的缘由, bind() 的实现,至关于使用函数在内部包了一个 call / apply ,第二次 bind() 至关于再包住第一次 bind() ,故第二次之后的 bind 是没法生效的。
apply、call、bind比较
那么 apply、call、bind 三者相比较,之间又有什么异同呢?什么时候使用 apply、call,什么时候使用 bind 呢。简单的一个栗子:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
var
obj = {
x: 81,
};
var
foo = {
getX:
function
() {
return
this
.x;
}
}
console.log(foo.getX.bind(obj)());
//81
console.log(foo.getX.call(obj));
//81
console.log(foo.getX.apply(obj));
//81
|
三个输出的都是81,可是注意看使用 bind() 方法的,他后面多了对括号。
也就是说,区别是,当你但愿改变上下文环境以后并不是当即执行,而是回调执行的时候,使用 bind() 方法。而 apply/call 则会当即执行函数。
再总结一下:
- apply 、 call 、bind 三者都是用来改变函数的this对象的指向的;
- apply 、 call 、bind 三者第一个参数都是this要指向的对象,也就是想指定的上下文;
- apply 、 call 、bind 三者均可以利用后续参数传参;
- bind 是返回对应函数,便于稍后调用;apply 、call 则是当即调用 。
本文转自:http://www.cnblogs.com/coco1s/p/4833199.html