Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript typeof undefined in class

When I make a class:

class DialogueChoice
{
    constructor(text, resultFunc) //dialogue line text, function to call when selected
    {
        this.integer = 25;
        ...
    }
    test()
    {
        console.log(typeof(this.integer))
    }
}

I get undefined as the type instead of a number when calling test(). Why is this? what am I missing? It happens for the other members as well. As far as I can tell the class is losing all it’s members after the constructor? Trying to print the value results in undefined as well. The issue only occurs when the func is called through pixijs event system. Calling from the main body of the script is fine.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

How do you use your class, because to me it seems to work as expected?

class DialogueChoice
{
    constructor(text, resultFunc) //dialogue line text, function to call when selected
    {
        this.integer = 25;
    }
    test()
    {
        console.log(typeof(this.integer))
    }
}

var dc = new DialogueChoice();
dc.test();

When you pass the test method to another function that then calls it, you have to make sure to bind it to the original object that it is attached to. Otherwise the context for that method will be the global object window. Something like this:

someOtherFunction(dc.test.bind(dc));

Alternatively you can wrap it in another function:

someOtherFunction(() => dc.test());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading