Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

whitedragon101

macrumors 65816
Original poster
Sep 11, 2008
1,336
334
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
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>
 

olup

Cancelled
Oct 11, 2011
383
40
your runBadger function is invocted immediately like the testBadger function. If you run the runBadger function as an arrow function, it will work because you have added the eventListener.
JavaScript:
 runBadger = () =>    {
        alert("my badger run = "+this.myBadger);
    }
 

whitedragon101

macrumors 65816
Original poster
Sep 11, 2008
1,336
334
your runBadger function is invocted immediately like the testBadger function. If you run the runBadger function as an arrow function, it will work because you have added the eventListener.
JavaScript:
 runBadger = () =>    {
        alert("my badger run = "+this.myBadger);
    }

Thanks for the help. Although when I replaced the runBadger method with the code from your post I got an error

"SyntaxError: Unexpected token '='. Expected an opening '(' before a method's parameter list."

It seems to be the = after runBadger its having a problem with. But if I remove it the error than changes to having an issue with the =>
 

olup

Cancelled
Oct 11, 2011
383
40
I suppose you were using Safari, I had only tested it in Chrome and since this is an ES6 feature I thought that it would also be supported natively in Safari, which it isn't. You need to include babel as an additional script to your HTML, in that case to make it work in Safari as well. I have just tested this in Safari 13.1.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.