JavaScript this 關鍵詞
實例
var person = { firstName: "Bill", lastName : "Gates", id : 678, fullName : function() { return this.firstName + " " + this.lastName; } };
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
指的是全局對象 [object Window]
。
實例
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; } };
實例
var person = { firstName: "Bill", lastName : "Gates", id : 678, fullName : function() { return this.firstName + " " + this.lastName; } };
換句話說,this.firstName 意味著 this(person)對象的 firstName 屬性。
顯式函數綁定
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"