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方法,那么我們可以通過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沒有某個(gè)方法(如本例中banana沒有say方法),但是其他的有(如本例中apple有say方法),我們可以借助call或apply用其他對(duì)象的方法來操作。
apply、call的區(qū)別
對(duì)于apply、call二者而言,作用完全一樣,只是接收參數(shù)的方式有所不同。如下面一個(gè)函數(shù):
var func = function (arg1, arg2) {
};
若要用apply方法來調(diào)用,則為:
func.call(this, [arg1, arg2]);
若要用call方法來調(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本身沒有max和min方法,但是Math有,我們就可以借助call或apply來使用其方法。
3. 驗(yàn)證是否是數(shù)組(前提是toString()方法沒有被重寫過)
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等方法。但我們可以通過Array.prototype.slice.call轉(zhuǎn)換為真正的數(shù)組的帶有l(wèi)ength是屬性的對(duì)象,這樣domNodes就可以應(yīng)用Array下的所有方法了。
簡(jiǎn)單面試題
定義一個(gè)log方法,讓它可以代理console.log方法,常見的解決辦法是:
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"
接下來的要求是給每一個(gè)log消息添加一個(gè)"(app)"前綴,比如:
log('hello world'); // (app)hello world
該怎么做比較優(yōu)雅呢?這時(shí)候需要想到arguments參數(shù)是個(gè)偽數(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);
}
log(1); // (app) 1
log(1,2,'msg'); // (app) 1 2 msg
bind方法
我們先來看一道題目:
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ì)象中拿出來,然后調(diào)用,并且希望this指向原來的對(duì)象。如果不做特殊處理,一般會(huì)丟失原來的對(duì)象,使用bind()方法能夠很漂亮的解決這個(gè)問題。
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()方法來綁定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ù)來調(diào)用原函數(shù)。
在常見的單體模式中,通常我們會(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(){}過渡到$('.someClass').on('click',function(event){})發(fā)生了改變,上述使用變量保存this這種方法是有用的,也沒有什么問題。當(dāng)然使用bind()方法可以更加優(yōu)雅地解決這個(gè)問題。
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ì)象。
再來一個(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ù)列表的開始位置,傳遞給綁定函數(shù)的參數(shù)會(huì)跟在它們后面。多說無益,來看例子:
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]
可見,利用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操作符來構(gòu)造目標(biāo)函數(shù)的實(shí)例。當(dāng)使用綁定函數(shù)來構(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 第五版才被加入;它可能無法在所有瀏覽器上運(yùn)行。這就需要我們自己實(shí)現(xiàn)bind()函數(shù)了。
首先我們可以通過給目標(biāo)函數(shù)指定作用域來簡(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》一書中對(duì)bind()的實(shí)現(xiàn):通過設(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í),說明返回的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è)有趣的問題,如果連續(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() 的實(shí)現(xiàn),相當(dāng)于使用函數(shù)在內(nèi)部包了一個(gè) call / apply ,第二次 bind() 相當(dāng)于再包住第一次 bind() ,故第二次以后的 bind 是無法生效的。
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)。
也就是說,區(qū)別是,當(dāng)你希望改變上下文環(huán)境之后并非立即執(zhí)行,而是回調(diào)執(zhí)行的時(shí)候,使用 bind() 方法。而 apply/call 則會(huì)立即執(zhí)行函數(shù)。
再總結(jié)一下:
apply 、 call 、bind 三者都是用來改變函數(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)用 。