說到 JavaScript 裡最容易讓人暈頭轉向的知識點,this 一定榜上有名,堪稱語言設計中著名的「坑」之一。有人甚至因為它太容易出錯而索性避開不用。
其實只要徹底搞懂 this 的工作原理,這些坑自然就能繞開。先說一個前提:this 本身並不複雜,它總是指向當前函數所屬的上下文對象,而且不能被賦值。如果你採用的是純函數式寫法而非面向對象,那麼代碼裡幾乎用不到 this。換句話說,只有當你在用對象/類的方式開發時,this 才真正有意義,否則它不過是函數調用時的副產品。
下面我們逐一看看不同場景下 this 究竟指向什麼。
alert(this) //window
在全局作用域中,this 指向全局對象,在瀏覽器環境下就是 window。
function fooCoder(x) { this.x = x; } fooCoder(2); alert(x); // 全局變量x值為2
這裡 this 指向了全局對象 window。需要注意的是,在嚴格模式下,此時的 this 會變成 undefined。
var name = "clever coder"; var person = { name : "foocoder", hello : function(sth){ console.log(this.name + " says " + sth); } } person.hello("hello world");
輸出結果是 foocoder says hello world。此時 this 指向 person 對象,也就是當前調用者。
new FooCoder();
當用 new 調用函數時,函數內部的 this 指向新創建出來的那個對象。
var name = "clever coder"; var person = { name : "foocoder", hello : function(sth){ var sayhello = function(sth) { console.log(this.name + " says " + sth); }; sayhello(sth); } } person.hello("hello world"); //clever coder says hello world
這是最容易讓人踩坑的地方:內部函數中的 this 並沒有按預期綁定到外層函數的對象上,而是綁定到了全局對象。這被普遍認為是 JavaScript 的設計缺陷,因為幾乎沒有人希望內部函數的 this 指向全局。常見的解決辦法是把外層的 this 用一個變量保存起來,約定俗成地命名為 that 或 self:
var name = "clever coder"; var person = { name : "foocoder", hello : function(sth){ var that = this; var sayhello = function(sth) { console.log(that.name + " says " + sth); }; sayhello(sth); } } person.hello("hello world"); //foocoder says hello world
person.hello.call(person, "world");
apply 和 call 用法類似,區別在於傳參方式:call 的參數是逐個列出,而 apply 的第二個參數是一個數組。
call( thisArg [,arg1,arg2,… ] ); // 參數列表 apply(thisArg [,argArray] ); // 參數數組
這兩種方法的本質都是把某個函數綁定到指定對象上執行,因此 this 會被顯式地設置為傳入的第一個參數。
把上面的情況歸納一下,可以濃縮成幾條規律:
1. 函數作為對象方法調用時,this 指向該對象。
2. 函數作為普通函數調用時,this 指向全局對象(嚴格模式下為 undefined)。
3. 構造函數中的 this 指向新創建的對象。
4. 嵌套函數中的 this 不會繼承外層函數的 this,如有需要,可用變量保存外層的 this。
再簡潔一點說:函數裡用到 this 時,只有當該函數被某個對象直接調用,this 才指向那個對象。
obj.foocoder(); foocoder.call(obj, ...); foocoder.apply(obj, …);
我們經常會寫這樣的代碼:
$("#some-ele").click = obj.handler;
如果 handler 內部用到了 this,它會綁定在 obj 上嗎?答案是否定的。賦值之後,函數是在回調中執行的,此時 this 會綁定到相應的 DOM 元素上。要理解這一點,需要理解函數的執行環境與作用域鏈,這裡不再展開,有興趣的讀者可以參考《JavaScript 高級程序設計》中的相關章節。
那麼該如何解決回調函數的綁定問題呢?ES5 引入了一個新方法 bind():
fun.bind(thisArg[, arg1[, arg2[, ...]]])
其中 thisArg 在綁定函數被調用時,會作為原函數運行時的 this 指向(當使用 new 調用綁定函數時該參數無效);而 arg1、arg2 等參數,會與綁定函數自身的參數按順序拼接後傳給原函數。
bind 方法創建的是一個新函數,稱為綁定函數,它會以創建時傳入的第一個參數作為 this。顯然,它能很好地解決上述問題:
$("#some-ele").click(person.hello.bind(person)); //相應元素被點擊時,輸出foocoder says hello world
這個方法其實很容易模擬,我們可以看看 Prototype.js 中 bind 方法的源碼:
Function.prototype.bind = function(){ var fn = this, args = Array.prototype.slice.call(arguments), object = args.shift(); return function(){ return fn.apply(object, args.concat(Array.prototype.slice.call(arguments))); }; };
讀完這篇文章,相信 this 對你來說已經不再是坑,而是一個可以清晰推理的規則了。