JS this 關鍵詞
this 是什麼?
JavaScript this
關鍵詞指的是它所屬的物件。
它擁有不同的值,具體取決於它的使用位置:
在方法中,this
指的是所有者物件。
單獨的情況下,this
指的是全域性物件。
在函式中,this
指的是全域性物件。
在函式中,嚴格模式下,this
是 undefined。
在事件中,this
指的是接收事件的元素。
像 call() 和 apply() 這樣的方法可以將 this
引用到任何物件。
方法中的 this
在物件方法中,this
指的是此方法的“擁有者”。
在本頁最上面的例子中,this
指的是 person 物件。
person 物件是 fullName 方法的擁有者。
fullName : function() {
return this.firstName + " " + this.lastName;
}
單獨的 this
在單獨使用時,擁有者是全域性物件,因此 this
指的是全域性物件。
在瀏覽器視窗中,全域性物件是 [object Window]
:
var x = this;
在嚴格模式中,如果單獨使用,那麼 this
指的是全域性物件 [object Window]:
"use strict";
var x = this;
函式中的 this(預設)
在 JavaScript 函式中,函式的擁有者預設繫結 this
。
因此,在函式中,this
function myFunction() {
return this;
}
函式中的 this(嚴格模式)
JavaScript 嚴格模式不允許預設繫結。
因此,在函式中使用時,在嚴格模式下,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 : "Bill",
lastName : "Gates",
id : 678,
myFunction : function() {
return this;
}
};
換句話說,this.firstName 意味著 this
(person)物件的 firstName 屬性。
var person = {
firstName: "Bill",
lastName : "Gates",
id : 678,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
顯式函式繫結
call() 和 apply() 方法是預定義的 JavaScript 方法。
它們都可以用於將另一個物件作為引數呼叫物件方法。
您可以在本教程後面閱讀有關 call() 和 apply() 的更多內容。
在下面的例子中,當使用 person2 作為引數呼叫 person1.fullName 時,this
將引用 person2,即使它是 person1 的方法:
var person1 = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
var person2 = {
firstName:"Bill",
lastName: "Gates",
}
person1.fullName.call(person2); // 會返回 "Bill Gates"