JavaScript 中的 this 關鍵詞
示例
const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
自己動手試一試 »
什麼是 this?
在 JavaScript 中,this
關鍵詞指向一個物件。
this
關鍵詞指向不同的物件,具體取決於它的使用方式。
在物件方法中,this 指向物件。 |
單獨使用時,this 指向全域性物件。 |
在函式中,this 指向全域性物件。 |
在嚴格模式下的函式中,this 是 undefined 。 |
在事件中,this 指向接收事件的元素。 |
諸如 call() 、apply() 和 bind() 等方法可以將 this 指向任何物件。 |
注意
this
不是一個變數。它是一個關鍵詞。你不能改變 this
的值。
方法中的 this
當在物件方法中使用時,this
指向物件。
在本頁頂部的例子中,this
指向 person 物件。
因為 fullName 方法是 person 物件的一個方法。
fullName : function() {
return this.firstName + " " + this.lastName;
}
自己動手試一試 »
單獨使用 this
當單獨使用時,this
指向全域性物件。
因為 this
在全域性作用域中執行。
在瀏覽器視窗中,全域性物件是 [object Window]
在嚴格模式下,當單獨使用時,this
也指向全域性物件
函式中的 this(預設)
在函式中,全域性物件是 this
的預設繫結。
在瀏覽器視窗中,全域性物件是 [object Window]
函式中的 this(嚴格模式)
JavaScript 嚴格模式不允許預設繫結。
因此,當在嚴格模式下的函式中使用時,this
是 undefined
。
事件處理程式中的 this
在 HTML 事件處理程式中,this
指向接收事件的 HTML 元素。
物件方法繫結
在這些例子中,this
是 person 物件
示例
const person = {
firstName : "John",
lastName : "Doe",
id : 5566,
myFunction : function() {
return this;
}
};
自己動手試一試 »
示例
const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
自己動手試一試 »
即 this.firstName 是 this(person 物件)的 firstName 屬性。
顯式函式繫結
call()
和 apply()
方法是預定義的 JavaScript 方法。
它們都可以用於以另一個物件作為引數呼叫物件方法。
下面的例子用 person2 作為引數呼叫 person1.fullName,this 指向 person2,即使 fullName 是 person1 的一個方法。
示例
const person1 = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
const person2 = {
firstName:"John",
lastName: "Doe",
}
// 返回 "John Doe"
person1.fullName.call(person2);
函數借用
透過 bind()
方法,一個物件可以借用另一個物件的方法。
這個例子建立了 2 個物件(person 和 member)。
member 物件借用了 person 物件的 fullname 方法
示例
const person = {
firstName:"John",
lastName: "Doe",
fullName: function () {
return this.firstName + " " + this.lastName;
}
}
const member = {
firstName:"Hege",
lastName: "Nilsen",
}
let fullName = person.fullName.bind(member);
自己動手試一試 »
this 優先順序
要確定 this
指向哪個物件;請使用以下優先順序順序。
優先順序 | 物件 |
1 | bind() |
2 | apply() 和 call() |
3 | 物件方法 |
4 | 全域性作用域 |
函式中的 this
是否使用 bind() 呼叫?
函式中的 this
是否使用 apply() 呼叫?
函式中的 this
是否使用 call() 呼叫?
函式中的 this
是否在物件函式(方法)中?
函式中的 this
是否在全域性作用域中。