JavaScript學習:JavaScript this 關鍵詞

使用this關鍵詞例子:
var person = {
firstName: “Bill”,
lastName : “Gates”,
id : 678,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
(this.firstName 意味着 this(person)對象的 firstName 屬性。)
一、this是什麼
JavaScript this 關鍵詞指的是它所屬的對象。
它擁有不同的值,具體取決於它的使用位置:
在方法中,this 指的是所有者對象。
單獨的情況下,this 指的是全局對象。
在函數中,this 指的是全局對象。
在函數中,嚴格模式下,this 是 undefined。
在事件中,this 指的是接收事件的元素。
像 call() 和 apply() 這樣的方法可以將 this 引用到任何對象。
二、方法中的this
在對象方法中,this 指的是此方法的“擁有者”。
上面的例子中,this 指的是 person 對象,person 對象是 fullName 方法的擁有者。
三、單獨的this
單獨使用時,擁有者是全局對象,this指的是全局對象,在瀏覽器窗口中,全局對象是[object window],在嚴格模式下單獨使用this,也是指全局對象。
例:
“use strict”;
var x = this;//[object window]
四、函數中的this
在 JavaScript 函數中,函數的擁有者默認綁定 this。
因此,在函數中,this 指的是全局對象 [object Window]。
例:
function myFunction() {
return this;
}
嚴格模式下,函數中的this是未定義的undefind,嚴格模式不允許默認綁定
五、事件處理程序中的this
在HTML事件處理程序中,this指的是接收此事件的HTML元素,例:
<button onclick="this.style.display='none'"> 點擊來刪除我! </button>
六、顯示函數綁定
call() 和 apply() 方法是預定義的 JavaScript 方法。
它們都可以用於將另一個對象作爲參數調用對象方法。
在下面的例子中,當使用 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”
W3School JavaScript this

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章