1

I have this piece of code:

class TestComponent {
  GenerateView() {
    var btntest = document.getElementById('btntest');
    btntest.onclick = function() {
      // this.test();  //this doesn't work
      alert("ok"); //this works

    }
  }
  test() {
    alert("ok");
  }

}
var d = new TestComponent();
d.GenerateView();
<div id="mydiv">
  <button id="btntest">test</button>
</div>

Why I can't use test function in onclick event for btntest? I have an error

this.test is not a function

When I didn't wrap in function, It worked.

Manas Khandelwal
  • 3,790
  • 2
  • 11
  • 24
laxsore
  • 143
  • 1
  • 2
  • 9
  • 3
    Does this answer your question? [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – evolutionxbox Mar 29 '21 at 14:45
  • 1
    `btntest.addEventListener("click", (evt) => { evt.preventDefault(); console.log(this); })` – epascarello Mar 29 '21 at 14:58

1 Answers1

1

The 'this' part of this.test refers to the btntest element and not your class.

A simple fix for this is make reference variable for your class in your generateView function.

GenerateView()
    {
        var THIS = this;
        var btntest = document.getElementById('btntest');
        btntest.onclick = function() {
            THIS.test();
        }
    }

J. Byvelds
  • 19
  • 4