更新時間:2022-07-21 09:48:14 來源:動力節點 瀏覽1241次
JavaScript中this關鍵字是什么?動力節點小編給大家舉例說明。
const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
在 JavaScript 中,this關鍵字指的是一個對象。
哪個對象取決于this調用(使用或調用)的方式。
this關鍵字根據其使用方式指代不同的對象:
在對象方法中,this指的是對象。
單獨,this指的是全局對象。
在函數中,this指的是全局對象。
在嚴格模式下的函數中,this是undefined.
在一個事件中,this指的是接收到該事件的元素。
像call()、apply()和這樣的方法bind()可以引用任何對象。this
在對象方法中使用時,this指的是對象。
在頂部的示例中,this指的是person對象。
因為fullName方法是person對象的方法。
fullName : function() {
return this.firstName + " " + this.lastName;
}
單獨使用時,this指的是全局對象。
因為this是在全局范圍內運行的。
在瀏覽器窗口中,全局對象是[object Window]:
let x = this;
在嚴格模式下,單獨使用時,this也指全局對象:
"use strict";
let x = this;
在函數中,全局對象是this.
在瀏覽器窗口中,全局對象是[object Window]:
function myFunction() {
return this;
}
JavaScript嚴格模式不允許默認綁定。
因此,當在函數中使用時,在嚴格模式下,this是undefined.
"use strict";
function myFunction() {
return this;
}
在 HTML 事件處理程序中,this指的是接收到事件的 HTML 元素:
<button onclick="this.style.display='none'">
Click to Remove Me!
</button>
在這些示例中,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(人對象)的firstName屬性。
call()和apply()方法是預定義的 JavaScript 方法。
它們都可以用來調用以另一個對象為參數的對象方法。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習