-1

When you click the text But no success when you click me, an error occurs. I know why the error occurs. My question is what is the best fix? The error occurs because when x.a is called when mydiv is clicked, this is mydiv. How can we make it so that x.a runs successfully when mydiv is clicked?

<!DOCTYPE html>
    <html>
    <head>
     <title></title>
    </head>
    <body>
     <div id="mydiv">But no success when you click me</div>
    
     <script>
      var x = new Thing();
      var y = document.getElementById('mydiv');
      x.a();
      y.addEventListener('click', x.a, false);
      
      function Thing() {
       this.a=function() {
        this.b();
       }
    
       this.b=function() {
        alert('Success');
       }
      }
     </script>
    </body>
    </html>
vatz88
  • 2,422
  • 2
  • 14
  • 25
Jim Andrews
  • 375
  • 1
  • 2
  • 14

1 Answers1

2

y.addEventListener('click', x.a.bind(x), false);

When you bind an event listener to a method, at the time the method is called (when you click on a div/button) this is going to reflect the context from which the method has been called.

gor181
  • 1,988
  • 1
  • 14
  • 12
  • Thanks, gor181. That works well. That makes the value of 'this' be x rather than mydiv when you click mydiv and x.a is executed. – Jim Andrews Feb 24 '17 at 07:33
  • @JimAndrews Yes, he knows why it works. That's why he posted the answer. –  Feb 24 '17 at 10:16