DIV CSS 佈局教程網

JavaScript的this綁定:call、apply、bind、new 一次講透
編輯:關於JavaScript     

this 大概是 JavaScript 裡最耐人尋味的特性。理解它的第一步,是先記住一句話:this 既不指向函式本身,也不指向它的作用域;this 是在函式被呼叫的當下才決定的,取決於「在哪裡、怎麼被呼叫」。

為什麼需要綁定 this

同一個函式用不同方式呼叫,this 指向的東西就不一樣:

 var info = "This is global info";
 var obj = {
 info: 'This is local info',
 getInfo: getInfo
 }
 function getInfo() {
 console.log(this.info);
 }
 obj.getInfo() //This is local info
 getInfo() //This is global info

這個例子說明了兩件事:一、同一個函式呼叫方式不同,this 的指向就不同,結果自然不同;二、當物件屬性的值是函式引用時,this 不會永遠綁在原物件上。

this 也會「不經意間丟失」

 var info = "This is global info";
 var obj = {
 info: 'This is local info',
 getInfo: function getInfo() {
 console.log(this.info);
 var getInfo2 = function getInfo2() {
 console.log(this.info);
 }
 getInfo2();
 }
 }
 obj.getInfo();
 //This is local info
 //This is global info

函式裡再定義函式,內層的 this 被指向了 window,於是拿不到外層物件的 info。最經典的解法是把外層 this 存進一個變數:

 var info = "This is global info";
 var obj = {
 info: 'This is local info',
 getInfo: function getInfo() {
 console.log(this.info);
 var self = this; //將外層this保存到變量中
 var getInfo2 = function getInfo2() {
 console.log(self.info); //指向外層變量代表的this
 }
 getInfo2();
 }
 }
 obj.getInfo();
 //This is local info
 //This is local info

但 self = this 這種寫法也有代價:它等於多引用了一次物件,某些情況下可能被誤改;需要多個環境的 this 時還得宣告多個變數,不好管理。所以我們需要更直接的綁定手段。

方法一:call 與 apply

兩者都定義在 Function.prototype 上,作用是修正函式執行時的上下文:

 var anotherFun = obj.getInfo;
 anotherFun.call(obj); //This is local info

簽名如下:

Function.prototype.call(context [, argument1, argument2 ])
Function.prototype.apply(context [, [ arguments ] ])

第一個參數是重新指定的上下文,必填;差別在後續參數的形式——call 是逐一列出,apply 是收在一個陣列裡:

 function add(num1, num2, num3) {
 return num1 + num2 + num3;
 }
 add.call(null, 10, 20, 30); //60
 add.apply(null, [10, 20, 30]); //60

當 context 傳入 undefined 或 null 時,會自動修正為全域物件(此處為 window)。

方法二:bind

ES5 在 Function.prototype 新增了 bind,它傳入一個上下文物件,回傳一個新的函式副本,並把該函式永遠綁定在這個上下文中。它也接受後續參數,可以順便做柯里化:

 Function.prototype.bind(context[, argument1, argument2])
 function add(num1, num2) {
 return num1 + num2;
 }
 var anotherFun = window.add.bind(window, 10);
 anotherFun(20); //30
 var anotherFun = obj.getInfo.bind(obj);
 anotherFun(); //This is local info

因為綁定後無法再用 call / apply 改回來,這種方式也被稱為硬綁定。

不支援 ES5 的舊環境則需要 polyfill:

 if (!Function.prototype.bind) {
 Function.prototype.bind = function (obj) {
 var self = this;
 return function () {
 self.call(obj);
 }
 }
 }

上面這版實現了「回傳函式 + 修正上下文」,但沒有柯里化。補上參數轉發:

 Function.prototype.bind = function(obj) {
 var args = Array.prototype.slice.call(arguments, 1); //記錄下所有第一次傳入的參數
 var self = this;
 return function () {
 self.apply(obj, args.concat(Array.prototype.slice.call(arguments)));
 }
 }

方法三:new 關鍵字

函式有兩種呼叫方式:直接呼叫,或用 new 做構造呼叫。

 function fun(){ console.log("function called"); }
 fun(); //function called
 var obj = new fun(); //function called

new 其實就是在原本呼叫的基礎上多做幾個步驟,其中一步正是把 this 修正到新產生的物件上:

 var a = 5;
 function Fun() { this.a = 10; }
 var obj = new Fun();
 obj.a //10

優先級怎麼比

先看 call/apply 對上預設指向,毫無懸念:

 obj1.getInfo() //this is obj1
 obj2.getInfo() //this is obj2
 obj1.getInfo.call(obj2) //this is obj2
 obj2.getInfo.call(obj1) //this is obj1

那 new 和 call/apply 誰贏?我們沒辦法寫出 new function.call(something) 這種程式碼,所以改用 bind 回傳的函式來間接測試:

 var obj = {};
 function foo(num){ this.num = num; }
 var setNum = foo.bind(obj);
 setNum(10);
 obj.num //10
 var obj2 = new setNum(20);
 obj.num //10
 obj2.num //20

結論很清楚:new 的優先級高於 bind。用 new 呼叫時會產生新物件並把 this 指向它,原本被 bind 綁定的物件完全不受影響。

也因此,前面自己寫的簡易 polyfill 並不具備這種能力。MDN 版本用了更完整的技巧:

 if (!Function.prototype.bind) {
 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 ? this : oThis || this,
 aArgs.concat(Array.prototype.slice.call(arguments)));
 };
 fNOP.prototype = this.prototype;
 fBound.prototype = new fNOP();
 return fBound;
 };
 }

它先檢查被綁定的物件是否為函式,避免 Function.prototype.bind.call(something) 傳入非函式時拋出未知錯誤;接著讓 fBound 透過 this instanceof fNOP 判斷是否處於 new 情境,是則用 this,否則用 oThis,同時設定原型鏈以維持 instanceof 的正確行為。

箭頭函式:this 不會被改變

ES6 的箭頭函式內部 this 永遠指向外層詞法作用域,call / apply / bind 都改不動它:

 var obj = {
 num: 1,
 getNum: function () {
 return function () {
 console.log(this.num); //此處的this指向window
 }
 }
 }
 obj.getNum()(); //undefined
 var obj2 = {
 num: 2,
 getNum: function () {
 return () => console.log(this.num); //箭頭函式內部綁定外部getNum的this
 }
 }
 obj2.getNum()(); //2

軟綁定:想要 bind 但保留二次修正的能力

如果希望有 bind 的效果,同時還能用 call / apply 再改一次,可以自己實作一個「軟綁定」:

 if (!Function.prototype.softBind) {
 Function.prototype.softbind = function (obj) {
 var self = this;
 var args = Array.prototype.slice.call(arguments, 1);
 return function () {
 return self.apply((!this || this === (window || global)) ? obj : this,
 args.concat(Array.prototype.slice.call(arguments)));
 }
 }
 }

判斷條件是「若 this 為空或等於全域物件,就用預設綁定,否則尊重當下的 this」,這樣就保留了被 call / apply 覆寫的空間。

bind 與 call 的實用技巧

把偽陣列轉成真陣列時常寫 Array.prototype.slice.call(arguments),但每次打這麼長很累,於是有人簡化成:

 var slice = Array.prototype.slice;
 slice(arguments); //error

同樣的問題也出現在:

 var qsa = document.querySelectorAll;
 qsa(something); //error

原因在於 slice 與 querySelectorAll 內部都用到 this,單獨引用時 this 在執行期變成了全域物件 window,自然就錯了。用 bind 就能造出一個帶著正確上下文的函式副本:

 var qsa = document.querySelectorAll.bind(document);
 qsa(something);

更妙的是,call 與 apply 本身也是函式,所以可以在它們上面再呼叫 bind,得到一個「預先綁好 slice 與指定上下文」的函式:

 var slice = Function.prototype.call.bind(Array.prototype.slice);
 slice(arguments);

總結

把優先級記住就不容易出錯:new > bind(硬綁定)> call / apply > 物件方法呼叫 > 預設指向;箭頭函式則完全不吃這一套,它的 this 由詞法作用域決定。日常開發中,遇到 this 指向不如預期時,先問自己「這個函式是怎麼被呼叫的」,答案通常就在那裡。

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