How to access 'this' keyword inside an arrow function in JavaScript?


"this" keyword in an arrow function

The JavaScript 'this' keyword refers to the object it belongs to. In an arrow function, 'this' belongs to a global object. Inside a simple function, there might be chances that 'this' keyword can result in undefined but in an arrow function it results in an exact value.

Example

Live Demo

<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>

Output

Hi, I'm picaso from seventh grade

Updated on: 01-Aug-2019

467 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements