Languages
[Edit]
EN

JavaScript - how to access this object inside event method?

2 points
Created by:
AnnLen
1777

Most common problem for new developers that try programming in JavaScript is usage this in propper way. In JavaScript it is possible to access object inside call back in following ways.

1. self / additional variable example

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <button id="clicker">Click me!</button>
  <script>

    var handle = document.getElementById('clicker');
    
    var MessageManager = {
      message: 'This is example message...',
      assignClickEvent: function(handle) {
          var self = this;
          
          handle.addEventListener('click', function() {
            alert(self.message);
          });
      }
    };

    MessageManager.assignClickEvent(handle);
    
  </script>
</body>
</html>

Note: this used inside click event function indicates for button element to solve this problem self variable has been used.

Result:

Function and self variable usage example
Function and self variable usage example

2. Function bind method example

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <button id="clicker">Click me!</button>
  <script>

    var handle = document.getElementById('clicker');
    
    var MessageManager = {
      message: 'This is example message...',
      assignClickEvent: function(handle) {

          function onClick() {
            alert(this.message);
          }

          handle.addEventListener('click', onClick.bind(this));
      }
    };

    MessageManager.assignClickEvent(handle);
    
  </script>
</body>
</html>

Note: by using onClick.bind method we create proxy instance for onClick function that will be called later with new context - in this case this indicates to MessageManager object.

Result:

Function bind method and this example
Function bind method and this example

3. ES6 and arrow function example

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <button id="clicker">Click me!</button>
  <script>

    var handle = document.getElementById('clicker');
    
    var MessageManager = {
      message: 'This is example message...',
      assignClickEvent: function(handle) {

          handle.addEventListener('click', () => {
            alert(this.message);
          });
      }
    };

    MessageManager.assignClickEvent(handle);
    
  </script>
</body>
</html>

Note: with arrow function we can use still this with parent context.

Result:

Arrow function with this context example
Arrow function with this context example
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.