How to use "this" keyword inside event listener inside a method of a class without losing access to class arguments and method arguments?

I am trying to learn the "this" keyword use in various contexts and so far all resources I found including the similar questions raised here in stackoverflow are confusing to me. These include some approach using .bind and .proxy methods. Hopefully someone has a clearer explanation on how to solve the problem described in the comment on the attached code snippet.

class Entity {
  constructor(entityArgs) {
    this.entityArgs = entityArgs;
  }
  method(methodArgs) {
    $('.button').on('click', function(event) {
      event.preventDefault();
      // Should return the button clicked. Codes seem to work
      $('#result').append('<br> clicked: ' + $(this).text() + '<br>');
      // Should return 'testMethodArg' as per below . Codes seem to work
      $('#result').append('methodArgs: ' + methodArgs + '<br>');
      // Should return 'testEntityArg' as per below. NOT WORKING - this is the problem
      $('#result').append('entityArgs: ' + this.entityArgs + '<br>');
    })
  }
}

$(function() {
  const obj = new Entity('testEntityArg');
  obj.method('testMethodArg');
})
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <title>Document</title>
</head>

<body>
  <div>
    <button id=tgtButton1 class="button">
            Button1
        </button>
  </div>
  <br>
  <div>
    <button id=tgtButton2 class="button">
            Button2
        </button>
  </div>
  <div id='result'>
  </div>
</body>

</html>

92 thoughts on “How to use "this" keyword inside event listener inside a method of a class without losing access to class arguments and method arguments?”

  1. Pingback: ivermectin online