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