0

Is it possible to determine the type of a JavaScript object?

See the example below for more context:

var Cat = function() {this.numEyes=2;this.numLegs=4};
var c = new Cat();

How do we determine the type of c.

I am not looking for

(c instanceof Cat)

Essentially how would I get the string Cat given c.

Vitor Canova
  • 3,918
  • 5
  • 31
  • 55

2 Answers2

0

I think you are after the constructor name and not the type. Problem is the way you defined it will not work.

var Cat = function (){}; 
var c = new Cat(); 
console.log(c.constructor.name);  //""

If you name your function, you can get the name

var Dog = function Dog(){}; 
var d = new Dog(); 
console.log(d.constructor.name);  //Dog
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

In the original post formulation still visible in the revision history, Cat was defined without var, i.e.:

Cat = function() {this.numEyes=2;this.numLegs=4};

In this case, the constructor's name can be determined by iterating over the properties of the global object (window for browsers).

Cat = function() {this.numEyes=2;this.numLegs=4};
var c = new Cat();
alert(typeNameOf(c));

function typeNameOf(c) {
    for (name in window) {
        if (window[name] == Object.getPrototypeOf(c).constructor) return name;
    }
}

This should alert "Cat" in all modern browsers.

Community
  • 1
  • 1
GOTO 0
  • 42,323
  • 22
  • 125
  • 158