如何在 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

更新於:2019 年 8 月 1 日

522 次瀏覽

開啟您的職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.