如何在 JavaScript 中的箭頭函式內訪問“this”關鍵字?
箭頭函式中的“this”關鍵字
JavaScript“this”關鍵字指其所屬的物件。在箭頭函式中,“this”屬於全域性物件。在簡單函式內,“this”關鍵字可能導致undefined,但在箭頭函式中,它會導致明確值。
示例
<html>
<body>
<script>
function Student(fname, grade) {
this.fname = fname;
this.grade = grade;
this.details = function() {
return () => {
document.write(`Hi, I'm ${this.fname} from ${this.grade} grade`);
};
}
}
let info = new Student('picaso', 'seventh');
let printInfo = info.details();
printInfo();
</script>
</body>
</html>輸出
Hi, I'm picaso from seventh grade
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP