0

Here I have a very simple class and I have a constructor inside of it and in constructor I am declaring a value donut_count but when I try to access that value in another function it says undefined why it is undefined:

class DonutMaker {
  constructor() {
    var donut_count = 1;
    this.target = document.getElementById("donut_creater");
    this.target.addEventListener("click", this.donutCreate);
  }
  donutCreate() {
    console.log(this.donut_count);
  }
}

let obj1 = new DonutMaker();
Ayan Khan
  • 53
  • 6
  • `this.donutCreate` should be `() => this.donutCreate()` – gog Jan 04 '23 at 11:05
  • is there a canonical dupe for this? – gog Jan 04 '23 at 11:06
  • @gog - Yes: http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback I often add [this one](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) as well, for broader context. – T.J. Crowder Jan 04 '23 at 11:06

0 Answers0