bind 是返回對應(yīng)函數(shù),便于稍后調(diào)用冗澈;apply 钦勘、call 則是立即調(diào)用 。
apply亚亲、call
在 javascript 中彻采,call
和 apply
都是為了改變某個函數(shù)運行時的上下文(context)而存在的,換句話說捌归,就是為了改變函數(shù)體內(nèi)部 this
的指向颊亮。
JavaScript 的一大特點是,函數(shù)存在「定義時上下文」和「運行時上下文」以及「上下文是可以改變的」這樣的概念陨溅。
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
方法:
banana = {
color: "yellow"
}
apple.say.call(banana); //My color is yellow
apple.say.apply(banana); //My color is yellow
所以,可以看出 call
和 apply
是為了動態(tài)改變 this
而出現(xiàn)的门扇,當(dāng)一個 object
沒有某個方法(本栗子中banana
沒有say
方法)雹有,但是其他的有(本栗子中apple
有say
方法)偿渡,我們可以借助call
或apply
用其它對象的方法來操作。
apply霸奕、call 區(qū)別
對于 apply
溜宽、call
二者而言,作用完全一樣质帅,只是接受參數(shù)的方式不太一樣适揉。例如,有一個函數(shù)定義如下:
var func = function(arg1, arg2) {
};
就可以通過如下方式來調(diào)用:
func.call(this, arg1, arg2);
func.apply(this, [arg1, arg2])
其中 this
是你想指定的上下文煤惩,他可以是任何一個 JavaScript 對象(JavaScript 中一切皆對象)嫉嘀,call
需要把參數(shù)按順序傳遞進(jìn)去,而 apply
則是把參數(shù)放在數(shù)組里魄揉〖粑辏
為了鞏固加深記憶,下面列舉一些常用用法:
apply洛退、call實例
數(shù)組之間追加
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]
獲取數(shù)組中的最大值和最小值
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 使用其方法兵怯。
驗證是否是數(shù)組(前提是toString()
方法沒有被重寫過)
functionisArray(obj){
return Object.prototype.toString.call(obj) === '[object Array]' ;
}
類(偽)數(shù)組使用數(shù)組方法
var domNodes = Array.prototype.slice.call(document.getElementsByTagName("*"));
Javascript中存在一種名為偽數(shù)組的對象結(jié)構(gòu)彩匕。比較特別的是 arguments
對象,還有像調(diào)用 getElementsByTagName
, document.childNodes
之類的媒区,它們返回NodeList
對象都屬于偽數(shù)組驼仪。不能應(yīng)用 Array下的 push
, pop
等方法。
但是我們能通過 Array.prototype.slice.call
轉(zhuǎn)換為真正的數(shù)組的帶有 length
屬性的對象驻仅,這樣 domNodes
就可以應(yīng)用 Array 下的所有方法了谅畅。
面試題
定義一個 log
方法登渣,讓它可以代理 console.log
方法噪服,常見的解決方法是:
function log(msg) {
console.log(msg);
}
log(1); //1
log(1,2); //1
上面方法可以解決最基本的需求,但是當(dāng)傳入?yún)?shù)的個數(shù)是不確定的時候胜茧,上面的方法就失效了粘优,這個時候就可以考慮使用 apply
或者 call
,注意這里傳入多少個參數(shù)是不確定的呻顽,所以使用apply
是最好的雹顺,方法如下:
function log(){
console.log.apply(console, arguments);
};
log(1); //1
log(1,2); //1 2
接下來的要求是給每一個 log
消息添加一個"(app)"的前輟,比如:
log("hello world"); //(app)hello world
該怎么做比較優(yōu)雅呢?這個時候需要想到arguments
參數(shù)是個偽數(shù)組廊遍,通過 Array.prototype.slice.call
轉(zhuǎn)化為標(biāo)準(zhǔn)數(shù)組嬉愧,再使用數(shù)組方法unshift
,像這樣:
function log(){
var args = Array.prototype.slice.call(arguments);
args.unshift('(app)');
console.log.apply(console, args);
};
bind
在討論bind()
方法之前我們先來看一道題目:
var altwrite = document.write;
altwrite("hello");
結(jié)果:Uncaught TypeError: Illegal invocation
altwrite()
函數(shù)改變this
的指向global
或window
對象喉前,導(dǎo)致執(zhí)行時提示非法調(diào)用異常没酣,正確的方案就是使用bind()
方法:
altwrite.bind(document)("hello")
當(dāng)然也可以使用call()
方法:
altwrite.call(document, "hello")
綁定函數(shù)
bind()
最簡單的用法是創(chuàng)建一個函數(shù)王财,使這個函數(shù)不論怎么調(diào)用都有同樣的this值。常見的錯誤就像上面的例子一樣裕便,將方法從對象中拿出來绒净,然后調(diào)用,并且希望this
指向原來的對象偿衰。如果不做特殊處理挂疆,一般會丟失原來的對象。使用bind()
方法能夠很漂亮的解決這個問題:
this.num = 9;
var mymodule = {
num: 81,
getNum: function() {
console.log(this.num);
}
};
mymodule.getNum(); // 81
var getNum = mymodule.getNum;
getNum(); // 9, 因為在這個例子中下翎,"this"指向全局對象
var boundGetNum = getNum.bind(mymodule);
boundGetNum(); // 81
bind()
方法與 apply
和 call
很相似缤言,也是可以改變函數(shù)體內(nèi) this
的指向。
MDN的解釋是:bind()
方法會創(chuàng)建一個新函數(shù)漏设,稱為綁定函數(shù)墨闲,當(dāng)調(diào)用這個綁定函數(shù)時,綁定函數(shù)會以創(chuàng)建它時傳入 bind()
方法的第一個參數(shù)作為 this
郑口,傳入 bind()
方法的第二個以及以后的參數(shù)加上綁定函數(shù)運行時本身的參數(shù)按照順序作為原函數(shù)的參數(shù)來調(diào)用原函數(shù)鸳碧。
直接來看看具體如何使用,在常見的單體模式中犬性,通常我們會使用 _this
, that
, self
等保存 this
瞻离,這樣我們可以在改變了上下文之后繼續(xù)引用到它。 像這樣:
var foo = {
bar : 1,
eventBind: function(){
var _this = this;
$('.someClass').on('click',function(event) {
/* Act on the event */
console.log(_this.bar); //1
});
}
}
由于 Javascript 特有的機制乒裆,上下文環(huán)境在 eventBind:function(){ }
過渡到 $('.someClass').on('click',function(event) { })
發(fā)生了改變套利,上述使用變量保存 this
這些方式都是有用的,也沒有什么問題鹤耍。當(dāng)然使用 bind()
可以更加優(yōu)雅的解決這個問題:
var foo = {
bar : 1,
eventBind: function(){
$('.someClass').on('click',function(event) {
/* Act on the event */
console.log(this.bar); //1
}.bind(this));
}
}
在上述代碼里肉迫,bind()
創(chuàng)建了一個函數(shù),當(dāng)這個click
事件綁定在被調(diào)用的時候稿黄,它的 this
關(guān)鍵詞會被設(shè)置成被傳入的值(這里指調(diào)用bind()
時傳入的參數(shù))喊衫。因此,這里我們傳入想要的上下文 this
(其實就是 foo
)杆怕,到 bind()
函數(shù)中族购。然后,當(dāng)回調(diào)函數(shù)被執(zhí)行的時候陵珍, this
便指向 foo
對象寝杖。再來一個簡單的栗子:
var bar = function(){
console.log(this.x);
}
var foo = {
x:3
}
bar(); // undefined
var func = bar.bind(foo);
func(); // 3
這里我們創(chuàng)建了一個新的函數(shù) func
,當(dāng)使用 bind()
創(chuàng)建一個綁定函數(shù)之后互纯,它被執(zhí)行的時候瑟幕,它的 this
會被設(shè)置成 foo
, 而不是像我們調(diào)用 bar()
時的全局作用域。
偏函數(shù)(Partial Functions)
Partial Functions
也叫Partial Applications
只盹,這里截取一段關(guān)于偏函數(shù)的定義:
Partial application can be described as taking a function that accepts some number of arguments, binding values to one or more of those arguments, and returning a new function that only accepts the remaining, un-bound arguments.
這是一個很好的特性亿卤,使用bind()
我們設(shè)定函數(shù)的預(yù)定義參數(shù),然后調(diào)用的時候傳入其他參數(shù)即可:
function list() {
return Array.prototype.slice.call(arguments);
}
var list1 = list(1, 2, 3); // [1, 2, 3]
// 預(yù)定義參數(shù)37
var leadingThirtysevenList = list.bind(undefined, 37);
var list2 = leadingThirtysevenList(); // [37]
var list3 = leadingThirtysevenList(1, 2, 3); // [37, 1, 2, 3]
和setTimeout一起使用
function Bloomer() {
this.petalCount = Math.ceil(Math.random() * 12) + 1;
}
// 1秒后調(diào)用declare函數(shù)
Bloomer.prototype.bloom = function() {
window.setTimeout(this.declare.bind(this), 100);
};
Bloomer.prototype.declare = function() {
console.log('我有 ' + this.petalCount + ' 朵花瓣!');
};
var bloo = new Bloomer();
bloo.bloom(); //我有 5 朵花瓣!
注意:對于事件處理函數(shù)和setInterval
方法也可以使用上面的方法
綁定函數(shù)作為構(gòu)造函數(shù)
綁定函數(shù)也適用于使用new
操作符來構(gòu)造目標(biāo)函數(shù)的實例鹿霸。當(dāng)使用綁定函數(shù)來構(gòu)造實例排吴,注意:this
會被忽略,但是傳入的參數(shù)仍然可用懦鼠。
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.toString = function() {
console.log(this.x + ',' + this.y);
};
var p = new Point(1, 2);
p.toString(); // '1,2'
var emptyObj = {};
var YAxisPoint = Point.bind(emptyObj, 0/*x*/);
// 實現(xiàn)中的例子不支持,
// 原生bind支持:
var YAxisPoint = Point.bind(null, 0/*x*/);
var axisPoint = new YAxisPoint(5);
axisPoint.toString(); // '0,5'
axisPoint instanceof Point; // true
axisPoint instanceof YAxisPoint; // true
new Point(17, 42) instanceof YAxisPoint; // true
捷徑
bind()
也可以為需要特定this
值的函數(shù)創(chuàng)造捷徑钻哩。
例如要將一個類數(shù)組對象轉(zhuǎn)換為真正的數(shù)組,可能的例子如下:
var slice = Array.prototype.slice;
// ...
slice.call(arguments);
如果使用bind()
的話肛冶,情況變得更簡單:
var unboundSlice = Array.prototype.slice;
var slice = Function.prototype.call.bind(unboundSlice);
// ...
slice(arguments);
實現(xiàn)
上面的幾個小節(jié)可以看出bind()
有很多的使用場景街氢,但是bind()
函數(shù)是在 ECMA-262 第五版才被加入;它可能無法在所有瀏覽器上運行睦袖。這就需要我們自己實現(xiàn)bind()
函數(shù)了珊肃。
首先我們可以通過給目標(biāo)函數(shù)指定作用域來簡單實現(xiàn)bind()
方法:
Function.prototype.bind = function(context){
self = this; //保存this,即調(diào)用bind方法的目標(biāo)函數(shù)
return function(){
return self.apply(context,arguments);
};
};
考慮到函數(shù)柯里化的情況馅笙,我們可以構(gòu)建一個更加健壯的bind()
:
Function.prototype.bind = function(context){
var args = Array.prototype.slice.call(arguments, 1),
self = this;
return function(){
var innerArgs = Array.prototype.slice.call(arguments);
var finalArgs = args.concat(innerArgs);
return self.apply(context,finalArgs);
};
};
這次的bind()
方法可以綁定對象伦乔,也支持在綁定的時候傳參。
繼續(xù)董习,Javascript的函數(shù)還可以作為構(gòu)造函數(shù)烈和,那么綁定后的函數(shù)用這種方式調(diào)用時,情況就比較微妙了皿淋,需要涉及到原型鏈的傳遞:
Function.prototype.bind = function(context){
var args = Array.prototype.slice(arguments, 1),
F = function(){},
self = this,
bound = function(){
var innerArgs = Array.prototype.slice.call(arguments);
var finalArgs = args.concat(innerArgs);
return self.apply((this instanceof F ? this : context), finalArgs);
};
F.prototype = self.prototype;
bound.prototype = new F();
return bound;
};
這是《JavaScript Web Application》一書中對bind()
的實現(xiàn):通過設(shè)置一個中轉(zhuǎn)構(gòu)造函數(shù)F招刹,使綁定后的函數(shù)與調(diào)用bind()
的函數(shù)處于同一原型鏈上杠步,用new操作符調(diào)用綁定后的函數(shù)抬伺,返回的對象也能正常使用instanceof
螃概,因此這是最嚴(yán)謹(jǐn)?shù)?code>bind()實現(xiàn)衙传。
對于為了在瀏覽器中能支持bind()
函數(shù),只需要對上述函數(shù)稍微修改即可:
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function () {},
fBound = function () {
return fToBind.apply(
this instanceof fNOP && oThis ? this : oThis || window,
aArgs.concat(Array.prototype.slice.call(arguments))
);
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
有個有趣的問題砰奕,如果連續(xù) bind()
兩次元镀,亦或者是連續(xù) bind()
三次那么輸出的值是什么呢露泊?像這樣:
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()
的實現(xiàn),相當(dāng)于使用函數(shù)在內(nèi)部包了一個 call / apply
,第二次 bind()
相當(dāng)于再包住第一次 bind()
,故第二次以后的 bind
是無法生效的贡翘。
apply蹈矮、call、bind比較
那么 apply鸣驱、call泛鸟、bind
三者相比較,之間又有什么異同呢踊东?何時使用 apply北滥、call
,何時使用bind
呢闸翅。簡單的一個栗子:
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()
方法的,他后面多了對括號坚冀。
也就是說济赎,區(qū)別是,當(dāng)你希望改變上下文環(huán)境之后并非立即執(zhí)行记某,而是回調(diào)執(zhí)行的時候司训,使用 bind() 方法。而 apply/call 則會立即執(zhí)行函數(shù)液南。
再總結(jié)一下:
apply
豁遭、 call
、bind
三者都是用來改變函數(shù)的this對象的指向的贺拣;
apply
蓖谢、 call
、bind
三者第一個參數(shù)都是this要指向的對象譬涡,也就是想指定的上下文闪幽;
apply
、 call
涡匀、bind
三者都可以利用后續(xù)參數(shù)傳參盯腌;
bind
是返回對應(yīng)函數(shù),便于稍后調(diào)用陨瘩;apply
腕够、call
則是立即調(diào)用 。