Languages
[Edit]
EN

JavaScript - access this object inside event method

2 points
Created by:
Frida-Timms
607

In this article, we would like to show you how to use this in a proper way.

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
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join