I have set a variable here in the constructor but then when I print it from a method fired by an event listener it shows as undefined. Anyone know why and how to fix?
Copy paste code as is to test, html and javascript is a self contained example, no extra code needed to run.
I create an instance of the class at the bottom and then fire the testBadger method directly from the instance. It fires an alert and shows a value of 10. Perfect
But when runBadger method fires triggered by the event listener the alert shows 'undefined'
//No badgers were harmed in the making of this test
Copy paste code as is to test, html and javascript is a self contained example, no extra code needed to run.
I create an instance of the class at the bottom and then fire the testBadger method directly from the instance. It fires an alert and shows a value of 10. Perfect
But when runBadger method fires triggered by the event listener the alert shows 'undefined'
//No badgers were harmed in the making of this test
HTML:
<html>
<title>Var Test</title>
<body>
<div id="myDiv" style="width:200px; height:200px; background-color:#CC00CC "></div>
</body>
</html>
JavaScript:
<script>
class BadgerTest
{
constructor()
{
this.myBadger = 10;
document.getElementById('myDiv').addEventListener('click', this.runBadger);
}
testBadger()
{
alert("my badger test = "+this.myBadger);
}
runBadger()
{
alert("my badger run = "+this.myBadger);
}
}
mybadger = new BadgerTest();
mybadger.testBadger();
</script>