Languages
[Edit]
EN

JavaScript - how to access this object inside event method?

2 points
Created by:
AnnLen
9180

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
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join