bind是返回對(duì)應(yīng)函數(shù)宇葱,便于稍后調(diào)用;而apply與call則是立即調(diào)用刊头。
apply黍瞧、call
在JS中,call和apply都是為了改變某個(gè)函數(shù)運(yùn)行時(shí)的上下文(context)而存在的芽偏,換言之就是為了改變函數(shù)體內(nèi)部this的指向雷逆。JS的一大特點(diǎn)是,函數(shù)存在諸如“定義時(shí)上下文”污尉、“運(yùn)行時(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
但是如果我們有一個(gè)對(duì)象banana = { color: 'yellow' },我們不想對(duì)它重新定義say方法被碗,那么我們可以通過(guò)call或apply用apple的say方法:
var banana = {
color: 'yellow'
};
apple.say.call(banana); // My color is yellow
apple.say.apply(banana); // My color is yellow
可以看出call和apply是為了動(dòng)態(tài)改變this而出現(xiàn)的某宪,當(dāng)一個(gè)object沒(méi)有某個(gè)方法(如本例中banana沒(méi)有say方法),但是其他的有(如本例中apple有say方法)锐朴,我們可以借助call或apply用其他對(duì)象的方法來(lái)操作兴喂。
apply、call的區(qū)別
對(duì)于apply焚志、call二者而言衣迷,作用完全一樣,只是接收參數(shù)的方式有所不同酱酬。如下面一個(gè)函數(shù):
var func = function (arg1, arg2) {
};
若要用apply方法來(lái)調(diào)用壶谒,則為:
func.call(this, [arg1, arg2]);
若要用call方法來(lái)調(diào)用,則為:
func.call(this, arg1, arg2);
其中膳沽,this是你想指定的上下文汗菜,它可以是任何一個(gè)JS對(duì)象(JS中一切皆對(duì)象),call需要把參數(shù)按順序傳遞進(jìn)去挑社,而apply則是把參數(shù)放在數(shù)組里陨界。
apply、call實(shí)例
1. 數(shù)組之間追加
var array1 = [12, 'foo', {name:'Joe'}, -2458];
var array2 = ['Doe', 555, 100];
Array.prototype.push.apply(array1,array2);
console.log(array1); // array1 值為 [12 , "foo" , {name:"Joe"} , -2458 , "Doe" , 555 , 100]
2. 獲取數(shù)組中的最大值和最小值
var numbers = [5, 458, 120, -215];
var maxInNumbers = Math.max.apply(Math, numbers);
var minInNumbers = Math.min.call(Math, numbers[0], numbers[1], numbers[2], numbers[3]);
console.log('Max number is ' + maxInNumbers + ' and min number is ' + minInNumbers); // Max number is 458 and min number is -215
numbers本身沒(méi)有max和min方法痛阻,但是Math有菌瘪,我們就可以借助call或apply來(lái)使用其方法。
3. 驗(yàn)證是否是數(shù)組(前提是toString()方法沒(méi)有被重寫過(guò))
function isArray(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
}
console.log(isArray(numbers)); // true
4. 類(偽)數(shù)組使用數(shù)組方法
var domNodes = Array.prototype.slice.call(document.getElementsByTagName("*"));
JS中存在一種名為偽數(shù)組的對(duì)象結(jié)構(gòu)阱当。比較特別的是arguments對(duì)象麻车,還有像調(diào)用getElementsByTagName缀皱,document.childNodes之類的,它們返回NodeList對(duì)象都屬于偽數(shù)組动猬。不能應(yīng)用Array的push啤斗、pop等方法。但我們可以通過(guò)Array.prototype.slice.call轉(zhuǎn)換為真正的數(shù)組的帶有l(wèi)ength是屬性的對(duì)象赁咙,這樣domNodes就可以應(yīng)用Array下的所有方法了钮莲。
簡(jiǎn)單面試題
定義一個(gè)log方法,讓它可以代理console.log方法彼水,常見(jiàn)的解決辦法是:
function log(msg) {
console.log(msg);
}
log(1); // 1
log(1,2); // 1
上面方法可以解決最基本的需求崔拥,但當(dāng)傳入?yún)?shù)的個(gè)數(shù)是不確定的時(shí)候該方法就失效了,這是就可以考慮用apply或call凤覆,注意這里傳入多少個(gè)參數(shù)是不確定的链瓦,所以使用apply方法是最好的:
function log() {
console.log.apply(console, arguments);
}
log(1); // 1
log(1,2,'msg'); // 1 2 "msg"
接下來(lái)的要求是給每一個(gè)log消息添加一個(gè)"(app)"前綴,比如:
log('hello world'); // (app)hello world
該怎么做比較優(yōu)雅呢盯桦?這時(shí)候需要想到arguments參數(shù)是個(gè)偽數(shù)組慈俯,通過(guò)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);
}
log(1); // (app) 1
log(1,2,'msg'); // (app) 1 2 msg
bind方法
我們先來(lái)看一道題目:
var altwrite = document.write;
altwrite("hello");
結(jié)果:Uncaught TypeError: Illegal invocation
altwrite()函數(shù)改變this的指向global或window對(duì)象贴膘,導(dǎo)致執(zhí)行時(shí)提示非法調(diào)用異常,正確的方案就是使用bind()方法:
altwrite.bind(document)("hello");
當(dāng)然也可以使用call()或apply方法略号,畢竟其本質(zhì)是綁定this使this重新指回document:
altwrite.call(document, "hello");
altwrite.apply(document, ["hello"]);
綁定函數(shù)
bind()最簡(jiǎn)單的用法是創(chuàng)建一個(gè)函數(shù)刑峡,是這個(gè)函數(shù)不論怎么調(diào)用都有同樣的this值。在編程中經(jīng)常會(huì)碰到像上面一樣的錯(cuò)誤玄柠,將方法從對(duì)象中拿出來(lái)突梦,然后調(diào)用,并且希望this指向原來(lái)的對(duì)象羽利。如果不做特殊處理宫患,一般會(huì)丟失原來(lái)的對(duì)象,使用bind()方法能夠很漂亮的解決這個(gè)問(wèn)題铐伴。
this.num = 9;
var mymodule = {
num: 81,
getNum: function () {
console.log(this.num);
}
};
mymodule.getNum(); // 81
var getNum = mymodule.getNum;
getNum(); // 9,因?yàn)樵谶@個(gè)例子中,"this"指向全局對(duì)象
var boundGetNum = getNum.bind(mymodule); // 運(yùn)用bind()方法來(lái)綁定this指向mymodule
boundGetNum(); // 81
bind()方法與apply和call相似,也是可以改變函數(shù)體內(nèi)部this的指向俏讹。MDN的解釋是:bind()方法會(huì)創(chuàng)建一個(gè)新函數(shù)当宴,稱為綁定函數(shù),當(dāng)調(diào)用這個(gè)綁定函數(shù)時(shí)泽疆,綁定函數(shù)會(huì)以創(chuàng)建它時(shí)傳入bind()方法的第一個(gè)參數(shù)作為this户矢,傳入bind()方法的第二個(gè)以及以后的參數(shù)加上綁定函數(shù)運(yùn)行時(shí)本身的參數(shù)按照順序作為原函數(shù)的參數(shù)來(lái)調(diào)用原函數(shù)。
在常見(jiàn)的單體模式中殉疼,通常我們會(huì)使用_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
});
}
}
由于JS特有機(jī)制,上下文環(huán)境在eventBind:function(){}過(guò)渡到$('.someClass').on('click',function(event){})發(fā)生了改變挂洛,上述使用變量保存this這種方法是有用的礼预,也沒(méi)有什么問(wèn)題。當(dāng)然使用bind()方法可以更加優(yōu)雅地解決這個(gè)問(wèn)題虏劲。
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)建了一個(gè)函數(shù),當(dāng)這個(gè)click事件綁定在被調(diào)用的時(shí)候柒巫,它的this關(guān)鍵詞會(huì)被設(shè)置成被傳入的值(這里指調(diào)用bind()時(shí)傳入的參數(shù))励堡。因此,這里我們傳入想要的上下文this(其實(shí)就是foo)堡掏,到bind()函數(shù)中应结。然后,當(dāng)回調(diào)函數(shù)被執(zhí)行的時(shí)候泉唁,this便指向foo對(duì)象鹅龄。
再來(lái)一個(gè)簡(jiǎn)單了案例:
var bar = function () {
console.log(this.x);
};
var foo = {
x: 3
};
bar(); // undefined
var func = bar.bind(foo);
func(); // 3
此處我們創(chuàng)建了一個(gè)新的函數(shù)func,當(dāng)使用bind()創(chuàng)建一個(gè)綁定函數(shù)之后游两,它被執(zhí)行時(shí)砾层,其this會(huì)被設(shè)置成foo,而不是像我們調(diào)用bar()時(shí)的全局作用域贱案。
偏函數(shù)(Partial Functions)
bind()的另一個(gè)最簡(jiǎn)單的用法就是使一個(gè)函數(shù)擁有預(yù)設(shè)的初始參數(shù)肛炮。只要將這些參數(shù)(如果有的話)作為bind()的參數(shù)寫在this后面。當(dāng)綁定函數(shù)被調(diào)用時(shí)宝踪,這些參數(shù)會(huì)被插入到目標(biāo)函數(shù)的參數(shù)列表的開(kāi)始位置侨糟,傳遞給綁定函數(shù)的參數(shù)會(huì)跟在它們后面。多說(shuō)無(wú)益瘩燥,來(lái)看例子:
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]
可見(jiàn)秕重,利用bind()方法將list這個(gè)根據(jù)參數(shù)生成數(shù)組的方法添加了初始參數(shù)37,使其成為leadingThirtysevenList方法厉膀。
和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(); // 我有x朵花瓣!
注意:對(duì)于事件處理函數(shù)和setInterval方法也可以使用上面的方法服鹅。
綁定函數(shù)作為構(gòu)造函數(shù)
綁定函數(shù)也適用于使用new操作符來(lái)構(gòu)造目標(biāo)函數(shù)的實(shí)例凳兵。當(dāng)使用綁定函數(shù)來(lái)構(gòu)造實(shí)例,注意:this會(huì)被忽略企软,但傳入的參數(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*/);
// 實(shí)現(xiàn)中的例子不支持
// 原生bind支持:
var YAxisPoint = Point.bind(null, 0/*x*/);
var axisPoint = new YAxisPoint(5);
axisPoint.toString(); // '0,5'
console.log(axisPoint instanceof Point); // true; instanceof用于檢測(cè)構(gòu)造函數(shù)的prototype屬性是否出現(xiàn)在某個(gè)實(shí)例對(duì)象的原型鏈上
console.log(axisPoint instanceof YAxisPoint); // true
console.log(new Point(17, 42) instanceof YAxisPoint); // true
捷徑
bind()也可以為需要特定this值的函數(shù)創(chuàng)造捷徑。例如要將一個(gè)類數(shù)組對(duì)象轉(zhuǎn)換為真正的數(shù)組,可能的例子如下:
var slice = Array.prototype.slice;
// ...
slice.call(arguments);
如果使用bind()的話形庭,情況變得更簡(jiǎn)單:
var unboundSlice = Array.prototype.slice;
var slice = Function.prototype.call.bind(unboundSlice);
// ...
slice(arguments);
實(shí)現(xiàn)
上面的幾個(gè)小節(jié)可以看出bind()有很多的使用場(chǎng)景铅辞,但是bind()函數(shù)是在 ECMA-262 第五版才被加入;它可能無(wú)法在所有瀏覽器上運(yùn)行萨醒。這就需要我們自己實(shí)現(xiàn)bind()函數(shù)了斟珊。
首先我們可以通過(guò)給目標(biāo)函數(shù)指定作用域來(lái)簡(jiǎn)單實(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)建一個(gè)更加健壯的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()方法可以綁定對(duì)象倍宾,也支持在綁定的時(shí)候傳參。
繼續(xù)胜嗓,Javascript的函數(shù)還可以作為構(gòu)造函數(shù)高职,那么綁定后的函數(shù)用這種方式調(diào)用時(shí),情況就比較微妙了辞州,需要涉及到原型鏈的傳遞:
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》一書(shū)中對(duì)bind()的實(shí)現(xiàn):通過(guò)設(shè)置一個(gè)中轉(zhuǎn)構(gòu)造函數(shù)F怔锌,使綁定后的函數(shù)與調(diào)用bind()的函數(shù)處于同一原型鏈上,用new操作符調(diào)用綁定后的函數(shù)变过,返回的對(duì)象也能正常使用instanceof埃元,因此這是最嚴(yán)謹(jǐn)?shù)腷ind()實(shí)現(xiàn)。
對(duì)于為了在瀏覽器中能支持bind()函數(shù)媚狰,只需要對(duì)上述函數(shù)稍微修改即可:
if (!Function.prototype.bind) {
Function.prototype.bind = function(oThis) {
if (typeof this !== 'function') {
// closest thing possible to the ECMAScript 5
// internal IsCallable 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() {
// this instanceof fBound === true時(shí),說(shuō)明返回的fBound被當(dāng)做new的構(gòu)造函數(shù)調(diào)用
return fToBind.apply(this instanceof fBound
? this
: oThis,
// 獲取調(diào)用時(shí)(fBound)的傳參.bind 返回的函數(shù)入?yún)⑼沁@么傳遞的
aArgs.concat(Array.prototype.slice.call(arguments)));
};
// 維護(hù)原型關(guān)系
if (this.prototype) {
// Function.prototype doesn't have a prototype property
fNOP.prototype = this.prototype;
}
// 下行的代碼使fBound.prototype是fNOP的實(shí)例,因此
// 返回的fBound若作為new的構(gòu)造函數(shù),new生成的新對(duì)象作為this傳入fBound,新對(duì)象的__proto__就是fNOP的實(shí)例
fBound.prototype = new fNOP();
return fBound;
};
}
有個(gè)有趣的問(wèn)題岛杀,如果連續(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() 是無(wú)效的嗤形。更深層次的原因精偿, bind() 的實(shí)現(xiàn),相當(dāng)于使用函數(shù)在內(nèi)部包了一個(gè) call / apply 赋兵,第二次 bind() 相當(dāng)于再包住第一次 bind() ,故第二次以后的 bind 是無(wú)法生效的笔咽。
apply、call霹期、bind比較
那么 apply叶组、call、bind 三者相比較经伙,之間又有什么異同呢扶叉?何時(shí)使用 apply、call帕膜,何時(shí)使用 bind 呢枣氧。簡(jiǎn)單的一個(gè)栗子:
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
三個(gè)輸出的都是81,但是注意看使用 bind() 方法的垮刹,他后面多了對(duì)括號(hào)达吞。
也就是說(shuō),區(qū)別是荒典,當(dāng)你希望改變上下文環(huán)境之后并非立即執(zhí)行酪劫,而是回調(diào)執(zhí)行的時(shí)候,使用 bind() 方法寺董。而 apply/call 則會(huì)立即執(zhí)行函數(shù)覆糟。
再總結(jié)一下:
apply 、 call 遮咖、bind 三者都是用來(lái)改變函數(shù)的this對(duì)象的指向的滩字;
apply 、 call 御吞、bind 三者第一個(gè)參數(shù)都是this要指向的對(duì)象麦箍,也就是想指定的上下文;
apply 陶珠、 call 挟裂、bind 三者都可以利用后續(xù)參數(shù)傳參;
bind 是返回對(duì)應(yīng)函數(shù)揍诽,便于稍后調(diào)用诀蓉;apply 、call 則是立即調(diào)用 寝姿。