When you should not use JavaScript Arrow Functions?

JavascriptWeb DevelopmentObject Oriented Programming

The arrow functions should not be used as an object method because an arrow function does not have its own this. It takes this value of the enclosing lexical scope which is the window object instead of the object itself. This can cause problems as we would now be setting and accessing the window object properties instead of the intended object.

Following is the code showing when should you not use JavaScript arrow functions −

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 20px;
      font-weight: 500;
      color: blueviolet;
   }
</style>
</head>
<body>
<h1>When to not use the arrow functions</h1>
<br />
<div class="result"></div>
<br />
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to call the add() method of object obj</h3>
<script>
   let BtnEle = document.querySelector(".Btn");
   let resEle = document.querySelector(".result");
   let obj = {
      a: 22,
      b: 44,
      add: () => {
         return this.a + this.b;
      },
   };
   BtnEle.addEventListener("click", (event) => {
      resEle.innerHTML = `The sum of ${obj.a} and ${obj.b} = ${obj.add()}`;
   });
</script>
</body>
</html>

Output

On clicking the ‘CLICK HERE’ button −

raja
Published on 18-Jul-2020 07:43:20
Advertisements