Narendra V
Narendra V

Reputation: 605

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

Upvotes: 3

Views: 3533

Answers (3)

Bergi
Bergi

Reputation: 665080

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.

Upvotes: 1

Sorskoot
Sorskoot

Reputation: 10310

Have you tried just calling the toString() function?

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

In the following sample the result variable will contain "Demo" and the constructor won't be called:

class Demo {
    abc:any;
    constructor(a: number) {
        this.abc = a;
    }
}
var result = getType(Demo);

Upvotes: 0

joseeight
joseeight

Reputation: 924

Maybe this is what you are looking for?

function getClassName(obj){
  return obj.constructor.name;
}

Upvotes: 0

Related Questions