Blog>
Snippets

Arrow functions and lexical 'this'

Explain how arrow functions lexically bind 'this' based on the surrounding scope where they are defined.
<!DOCTYPE html>
<html>
<head>
<style>
  #myDiv {
    height: 30px;
    color: white;
    background: green;
  }
</style>
</head>
<body>

<div id='myDiv'>Initial text</div>

<script>
  class MyComponent {
    constructor(elementId) {
      this.elem = document.getElementById(elementId);
      this.text = 'Updated by Arrow Function';
    }

    updateText() {
      // Using arrow function to lexically bind 'this'
      setTimeout(() => {
        this.elem.textContent = this.text;
      }, 1000);
    }
  }

  const myComponent = new MyComponent('myDiv');
  myComponent.updateText();
</script>

</body>
</html>
This code snippet creates an HTML page with a green div, which text content is updated after 1 second by an arrow function inside a class. The class MyComponent has a constructor that sets up an element reference and a text to update the element with. The updateText method uses an arrow function within setTimeout to ensure 'this' refers to the instance of MyComponent (lexical this), so it can access the element and the text. This wouldn't have worked with a traditional function as 'this' would refer to the global object or the context of setTimeout.