this
是 Javascript 中的關鍵字。
在JavaScript中,函數的this關鍵字的行爲與其他語言相比有很多不同。在JavaScript的嚴格模式和非嚴格模式下也略有區別。
在絕大多數情況下,函數的調用方式決定了this的值。this不能在執行期間被賦值,在每次函數被調用時this的值也可能會不同。
全局上下文
在全局上下文中(在任何函數體外部),無論是在嚴格模式還是非
嚴格模式下,this都指代的是全局對象 window。
1 2 3 4 5 6 7
|
console.log(this.document === document); // true // 在瀏覽器中,全局對象爲 window 對象: console.log(this === window); // true this.a = 37; console.log(window.a); // 37
|
函數上下文
在函數內部,this的值取決於函數是如何調用的。
直接調用
1 2 3 4 5
|
function f1(){ return this; } f1() === window; // true
|
在上面的例子中,this的值不是由函數調用設定。因爲代碼不是在嚴格模式下執行,this 的值總是一個對象且默認爲全局對象。
1 2 3 4 5 6
|
function f2(){ // 這裏是嚴格模式 ; return this; } f2() === undefined; // true
|
在嚴格模式下,this 是在進入運行環境時設置的。若沒有定義,this的值將維持undefined狀態。同時它也能設置成任意值,比如 null 或者42 或者“I am not this”。
注意:在第二個例子中,this應該是undefined。因爲f2不是作爲方法調用的(見下文)。這個功能並未在所有第一次開始支持嚴格模式的瀏覽器中都得到了實現。因此有些瀏覽器返回了錯誤的結果 :window 對象。
對象方法中的 this
當以對象裏的方法的方式調用函數時,它們的 this 是調用該函數的對象.
下面的例子中,當 o.f() 被調用時,函數內的this將綁定到o對象。
1 2 3 4 5 6 7 8
|
var o = { prop: 37, f: function() { return this.prop; } }; console.log(o.f()); // logs 37
|
注意,在何處或者如何定義調用函數完全不會影響到this的行爲。在上一個例子中,我們在定義o的時候爲其成員f定義了一個匿名函數。但是,我們也可以首先定義函數然後再將其附屬到o.f。這樣做this的行爲也一致:
1 2 3 4 5 6 7 8 9
|
var o = {prop: 37}; function independent() { return this.prop; } o.f = independent; console.log(o.f()); // logs 37
|
這說明this的值只與函數 f 作爲 o 的成員被調用有關係。
類似的,this 的綁定只受最靠近的成員引用的影響。在下面的這個例子中,我們把一個方法g當作對象o.b的函數調用。在這次執行期間,函數中的this將指向o.b。事實上,這與對象本身的成員沒有多大關係,最靠近的引用纔是最重要的。
1 2 3 4 5
|
o.b = { g: independent, prop: 42 }; console.log(o.b.g()); // logs 42
|
原型鏈中的 this
相同的概念在定義在原型鏈中的方法也是一致的。如果該方法存在於一個對象的原型鏈上,那麼this指向的是調用這個方法的對象,表現得好像是這個方法就存在於這個對象上一樣。
1 2 3 4 5 6 7 8 9 10
|
var o = { f : function(){ return this.a + this.b; } }; var p = Object.create(o); p.a = 1; p.b = 4; console.log(p.f()); // 5
|
在這個例子中,對象p沒有屬於它自己的f屬性,它的f屬性繼承自它的原型。但是這對於最終在o中找到f屬性的查找過程來說沒有關係;查找過程首先從p.f的引用開始,所以函數中的this指向p。也就是說,因爲f是作爲p的方法調用的,所以它的this指向了p。這是JavaScript的原型繼承中的一個有趣的特性。
getter 與 setter 中的 this
再次,相同的概念也適用時的函數作爲一個 getter 或者 一個setter調用。作爲getter或setter函數都會綁定 this 到從設置屬性或得到屬性的那個對象。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
function modulus(){ return Math.sqrt(this.re * this.re + this.im * this.im); } var o = { re: 1, im: -1, get phase(){ return Math.atan2(this.im, this.re); } }; Object.defineProperty(o, 'modulus', { get: modulus, enumerable:true, configurable:true}); console.log(o.phase, o.modulus); // logs -0.78 1.4142
|
構造函數中的 this
當一個函數被作爲一個構造函數來使用(使用new關鍵字),它的this與即將被創建的新對象綁定。
注意:當構造器返回的默認值是一個this引用的對象時,可以手動設置返回其他的對象,如果返回值不是一個對象,返回this。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
/* * Constructors work like this: * * function MyConstructor(){ * // Actual function body code goes here. * // Create properties on |this| as * // desired by assigning to them. E.g., * this.fum = "nom"; * // et cetera... * * // If the function has a return statement that * // returns an object, that object will be the * // result of the |new| expression. Otherwise, * // the result of the expression is the object * // currently bound to |this| * // (i.e., the common case most usually seen). * } */ function C(){ this.a = 37; } var o = new C(); console.log(o.a); // logs 37 function C2(){ this.a = 37; return {a:38}; } o = new C2(); console.log(o.a); // logs 38
|
在最後的例子中(C2),因爲在調用構造函數的過程中,手動的設置了返回對象,與this綁定的默認對象被取消(本質上這使得語句“this.a = 37;”成了“殭屍”代碼,實際上並不是真正的“殭屍”,這條語句執行了但是對於外部沒有任何影響,因此完全可以忽略它)。
call 和 apply
當一個函數的函數體中使用了this關鍵字時,通過所有函數都從Function對象的原型中繼承的call()方法和apply()方法調用時,它的值可以綁定到一個指定的對象上。
1 2 3 4 5 6 7 8 9 10 11 12 13
|
function add(c, d){ return this.a + this.b + c + d; } var o = {a:1, b:3}; // The first parameter is the object to use as 'this', subsequent parameters are passed as // arguments in the function call add.call(o, 5, 7); // 1 + 3 + 5 + 7 = 16 // The first parameter is the object to use as 'this', the second is an array whose // members are used as the arguments in the function call add.apply(o, [10, 20]); // 1 + 3 + 10 + 20 = 34
|
使用 call 和 apply 函數的時候要注意,如果傳遞的 this 值不是一個對象,JavaScript 將會嘗試使用內部 ToObject 操作將其轉換爲對象。因此,如果傳遞的值是一個原始值比如 7 或 ‘foo’ ,那麼就會使用相關構造函數將它轉換爲對象,所以原始值 7 通過new Number(7)被轉換爲對象,而字符串’foo’使用 new String(‘foo’) 轉化爲對象,例如:
1 2 3 4 5
|
function bar() { console.log(Object.prototype.toString.call(this)); } bar.call(7); // [object Number]
|
bind 方法
ECMAScript 5 引入了 Function.prototype.bind。調用f.bind(someObject)會創建一個與f具有相同函數體和作用域的函數,但是在這個新函數中,this將永久地被綁定到了bind的第一個參數,無論這個函數是如何被調用的。
1 2 3 4 5 6 7 8 9
|
function f(){ return this.a; } var g = f.bind({a:"azerty"}); console.log(g()); // azerty var o = {a:37, f:f, g:g}; console.log(o.f(), o.g()); // 37, azerty
|
DOM事件處理函數中的 this
當函數被用作事件處理函數時,它的this指向觸發事件的元素(一些瀏覽器在動態添加監聽器時不遵守這個約定,除非使用addEventListener 這句不太確定翻譯的是否正確)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
// 被調用時,將關聯的元素變成藍色 function bluify(e){ console.log(this === e.currentTarget); // 總是 true // 當 currentTarget 和 target 是同一個對象是爲 true console.log(this === e.target); this.style.backgroundColor = '#A5D9F3'; } // 獲取文檔中的所有元素的列表 var elements = document.getElementsByTagName('*'); // 將bluify作爲元素的點擊監聽函數,當元素被點擊時,就會變成藍色 for(var i=0 ; i<elements.length ; i++){ elements[i].addEventListener('click', bluify, false); }
|
內聯事件處理函數中的 this
當代碼被內聯處理函數調用時,它的this指向監聽器所在的DOM元素:
1 2 3 4 5 6 7 8
|
<button onclick="alert(this.tagName.toLowerCase());"> Show this </button> 上面的alert會顯示button。注意只有外層代碼中的this是這樣設置的: <button onclick="alert((function(){return this})());"> Show inner this </button>
|
在這種情況下,沒有設置內部函數的 this,所以它指向 global/window 對象(即非嚴格模式下調用的函數未設置 this 時指向的默認對象)。