在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