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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With