Getting the name of a class constructed by an anonymous function

I need to work inside a namespace, say I make this

var my_namespace = {}

my_namespace.my_class = function() {}

var instance = new my_namespace.my_class();

Then the current problem I’m facing is that instance.constructor.name returns “” (an empty string).

I want to check the type of instance by comparing it against an array of possibilities such as ‘String’ or ‘Array’ or ‘my_namespace.my_class’

Theoretically I could work around it by using instanceof and eval but I’m looking for a less volatile way.

Answer

Have you considered not using an anonymous function? Something like:

var my_namespace = {};
my_namespace.my_class = function MyClass() {};
var instance = new my_namespace.my_class();

console.log(instance.constructor.name);

Leave a Reply

Your email address will not be published. Required fields are marked *