Search code examples
javascriptjqueryclasstypescriptprototype

Check if a Typescript class has already been instantiated


I'm almost new to Typescript (and also to OOP) and I have a module like the following:

module SIMULATOR {
    export class myClass extends myBaseClass{
        constructor(){
        //Make a div and append it to body
        }
    }
}

Than i have an element with onClick function that call myClass like this:

$(button).on('click', ()=> {
    if(//class hasn't been instantiated yet){
        var myDiv = new SIMULATOR.myClass();
    }
    else{
        //do other stuff (eg: delete myClass instance)
    }
});

My first goal is to understand how i can check if myClass has been already instantiated.

Later i will destroy the created div with jquery and i would like to know how to "destroy" myClass instance too.

I apologize if the questions may seem silly: I'm a beginner :)


Solution

  • Since you're using jQuery :), here's how I would do this:

    $(button).on('click', ()=> {
        var myDiv: SIMULATOR.myClass = $(button).data('myClass');
        if(myDiv){
            //do other stuff (eg: delete myClass instance)
        }
        else {
            // myDiv has not been instantiated
            myDiv = new SIMULATOR.myClass();
            $(button).data('myClass', myDiv)
        }
    });
    

    This actually stores the instance of the class in jQuery's data structure, in memory, not as a data- attribute. If the instance is in the data structure, you're good to go. If it's not, you create it and add it to the data structure.

    To remove the instance from the data structure, use $(button).data('myClass', null);.

    That won't dispose of the object, but will remove references of it so that the JavaScript engine will collect it as garbage.