Quasipickle
Quasipickle

Reputation: 4498

How to determine if a Javascript class has been declared?

I have some javascript that is being referenced via html that is loaded via AJAX (ie: AJAX retrieves HTML, HTML has a <script> tag in it that references this javascript)

This javascript contains class declarations, ex:

class CalculatorClass{
    ...
}

If this script gets loaded twice, I get an error: redeclaration of let CalculatorClass. Since it's not a variable, I can't test if it's undefined first - and even then it would restrict the scope. How do I only declare the class if it isn't already?

Upvotes: 5

Views: 2705

Answers (1)

Long M K Nguyễn
Long M K Nguyễn

Reputation: 817

You can check if a class is already declared using if (typeof MyClass === 'function')

Upvotes: 9

Related Questions