實體
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"
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/162081.html
標籤:JavaScript
上一篇:JS---封裝getScroll函式 & 案例:固定導航欄
下一篇:chrome 瀏覽器的使用技巧
