Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing object type in javascript

I am trying to store object type in to variable instead of creating actual object. Based on the type, I would like to create object when ever I needed.

I've tried the below method to get the type

function getType(obj){
        var text = Function.prototype.toString.call(obj.constructor);
        return text.match(/function (.*)\(/)[1];
}

But issue with above method, it calls constructor to the get the type name.

I don't want to initialize the object until i actually needed.

Any thoughts.

Thanks Naren

like image 321
Narendra V Avatar asked Dec 06 '25 05:12

Narendra V


1 Answers

I think you're looking for

function getType(fn) {
    return fn.name || fn.toString().match(/function\s+([^(\s]*)/)[1];
}

which can call both with

function Class() {}
getType(Class) // "Class"

or

var instance = new Class;
getType(instance.constructor) // "Class"

Notice that you should not use this in production. There are js implemenations that neither support name nor toString on functions. Set a custom .type property or so on your constructors where you need it.

like image 180
Bergi Avatar answered Dec 08 '25 18:12

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!