DIV CSS 佈局教程網

開啟 JavaScript 中 apply、call、bind 的用法之旅
編輯:關於JavaScript     

希望透過這篇文章,能清晰提升你對 apply、call、bind 的認識,並透過一些妙用加深記憶。

apply、call

在 JavaScript 中,call 與 apply 都是為了改變某個函式執行時的上下文(context)而存在,換句話說,就是為了改變函式體內部 this 的指向。

JavaScript 的一大特點是:函式存在「定義時上下文」與「執行時上下文」,而且「上下文是可以改變的」。

先來看一段程式碼範例:

 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 是為了動態改變 this 而出現的:當一個物件沒有某個方法(此例中 banana 沒有 say),但另一個物件有(此例中 apple 有 say),我們就能借助 call 或 apply 用其他物件的方法來操作。

apply、call 的區別

就 apply 與 call 而言,作用完全相同,只是接受參數的方式不同。例如有個函式定義如下:

 var func = function(arg1, arg2) { };

可以透過如下方式呼叫:

 func.call(this, arg1, arg2); func.apply(this, [arg1, arg2])

其中 this 是你想指定的上下文,它可以是任何一個 JavaScript 物件(JavaScript 中一切皆物件)。call 需要把參數按順序傳遞進去,而 apply 則是把參數放進陣列裡。

由於 JavaScript 函式的參數數量不固定,所以要說適用條件的話:當你明確知道參數數量時用 call;不確定時用 apply,把參數 push 進陣列再傳入。函式內部也可以透過 arguments 這個陣列來遍歷所有參數。

為了加深記憶,下面列舉一些常用用法:

1、陣列之間追加

 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] */

2、取得陣列中的最大值和最小值

 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 使用其方法。

3、驗證是否為陣列(前提是 toString() 方法沒有被重寫過)

 functionisArray(obj){ return Object.prototype.toString.call(obj) === '[object Array]' ; }

4、類(偽)陣列使用陣列方法

 var domNodes = Array.prototype.slice.call(document.getElementsByTagName("*"));

JavaScript 中存在一種名為偽陣列的物件結構,比較特別的是 arguments 物件,還有呼叫 getElementsByTagName、document.childNodes 之類返回的 NodeList 物件都屬於偽陣列,無法套用 Array 下的 push、pop 等方法。

但我們能透過 Array.prototype.slice.call 把它們轉換成真正的、帶有 length 屬性的陣列,這樣 domNodes 就能套用 Array 下的所有方法了。

深入理解與運用 apply、call

下面藉【一道面試題】來更深入理解 apply 與 call。

定義一個 log 方法,讓它可以代理 console.log,常見的解法是:

 function log(msg) { console.log(msg); } log(1); //1 log(1,2); //1

上面能解決最基本的需求,但當傳入參數個數不確定時就失效了。這時可以考慮用 apply 或 call,注意這裡傳入多少參數是不確定的,所以用 apply 最好,寫法如下:

 function log(){ console.log.apply(console, arguments); }; log(1); //1 log(1,2); //1 2

接下來的要求是給每個 log 訊息加上「(app)」的前綴,例如:

 log("hello world"); //(app)hello world

該怎麼優雅地做到呢?這時要想到 arguments 是個偽陣列,先透過 Array.prototype.slice.call 轉成標準陣列,再用陣列方法 unshift,像這樣:

 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,這樣在改變上下文後仍能繼續引用它,像這樣:

 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() 可以更優雅地解決這個問題:

 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 物件。再來一個簡單的例子:

 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() 兩次,甚至三次,輸出會是什麼呢?像這樣:

 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 呢?看一個簡單的例子:

 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 物件指向的;
三者第一個參數都是 this 要指向的物件,也就是想指定的上下文;
三者都可以利用後續參數傳參;

bind 是返回對應函式,便於稍後呼叫;apply、call 則是立即呼叫。

好了,關於 JavaScript 中 apply、call、bind 用法的介紹就到這裡,希望大家喜歡。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved