title: Adding Event Handler to Constructor method
body: <p>I am trying to make a class that creates a list element while attaching an event listener to it. The following is my code: </p>
  
  <pre><code>class listItem {
  
      constructor(id) {
          this.id = id;       
          this.li = $("&lt;li&gt;");
          this.li.text(this.id);
  
          // Selector
          this.li.on("click", function() {
              this.li.text("clicked");
          });
      }
  
      getDom() {
          return this.li;
      }
  }
  </code></pre>
  
  <p>I invoke this class using the following:</p>
  
  <pre><code>// Creating a new listElement and appending it to the list
  var l1 = new listItem(1);
  $("ul").append(l1.getDom());
  </code></pre>
  
  <p>However, when I click on the element, I get the following error message:</p>
  
  <blockquote>
    <p>Uncaught TypeError: Cannot read property 'text' of undefined</p>
    
    <blockquote>
      <p>at HTMLLIElement. ((index):56)</p>
      
      <p>at HTMLLIElement.dispatch (jquery.js:5206)</p>
      
      <p>at HTMLLIElement.elemData.handle (jquery.js:5014)</p>
    </blockquote>
  </blockquote>
  
  <p>Here is my jsfiddle of the <a href="https://jsfiddle.net/7ucxpmr1/3/" rel="nofollow noreferrer">code</a>.</p>