如何在 JavaScript 的箭头函数中访问"this"关键字?

javascriptobject oriented programmingfront end technology

箭头函数中的"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

相关文章