<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<canvas id="cv" style="border:2px solid black;">
<script>
class Click {
constructor() {
let cv = document.getElementById("cv");
this.cv = cv;
let x = 3;
this.x = x;
this.cv.addEventListener('click', this.f); //Line A
this.f(); //Line B
}
f() {
console.log(this.x);
}
}
new Click();
</script>
Line B displays the value of 3 to console. But line A displays 'undefined' because the same function is called by an eventListener.
If I remove all the objectoriented stuff e.g. constructor, class and 'this.', then it works. But it has to be objectoriented. Maybe I misused the 'this' keyword.