JavaScript this 關鍵字
面向對象語言中 this 表示當前對象的一個引用。
但在 JavaScript 中 this 不是固定不變的,它會隨著執行環境的改變而改變。
- 在方法中,this 表示該方法所屬的對象。
- 如果單獨使用,this 表示全局對象。
- 在函數中,this 表示全局對象。
- 在函數中,在嚴格模式下,this 是未定義的(undefined)。
- 在事件中,this 表示接收事件的元素。
- 類似 call() 和 apply() 方法可以將 this 引用到任何對象。
實例
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
方法中的 this
在對象方法中, this 指向調用它所在方法的對象。
在上面一個實例中,this 表示 person 對象。
fullName 方法所屬的對象就是 person。
實例
fullName : function() {
return this.firstName + " " + this.lastName;
}
單獨使用 this
單獨使用 this,則它指向全局(Global)對象。
在流覽器中,window 就是該全局對象為 [object Window]:
實例
var x = this;
嚴格模式下,如果單獨使用,this 也是指向全局(Global)對象。
實例
"use strict";
var x = this;
函數中使用 this(默認)
在函數中,函數的所屬者默認綁定到 this 上。
在流覽器中,window 就是該全局對象為 [object Window]:
實例
function myFunction() {
return this;
}
函數中使用 this(嚴格模式)
嚴格模式下函數是沒有綁定到 this 上,這時候 this 是 undefined。
實例
"use strict";
function myFunction() {
return this;
}
事件中的 this
在 HTML 事件句柄中,this 指向了接收事件的 HTML 元素:
實例
<button onclick="this.style.display='none'">
點我後我就消失了
</button>
對象方法中綁定
下麵實例中,this 是 person 對象,person 對象是函數的所有者:
實例
var person = {
firstName : "John",
lastName : "Doe",
id : 5566,
myFunction : function() {
return this;
}
};
實例
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
說明: this.firstName 表示 this (person) 對象的 firstName 屬性。
顯式函數綁定
在 JavaScript 中函數也是對象,對象則有方法,apply 和 call 就是函數對象的方法。這兩個方法異常強大,他們允許切換函數執行的上下文環境(context),即 this 綁定的對象。
在下面實例中,當我們使用 person2 作為參數來調用 person1.fullName 方法時, this 將指向 person2, 即便它是 person1 的方法:
實例
var person1 = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
var person2 = {
firstName:"John",
lastName: "Doe",
}
person1.fullName.call(person2); // 返回 "John Doe"