How to know what is the class name of a javascript object?

Asked

Viewed 1,310 times

2

In PHP we can find out which instance an object is coming from through the function get_class.

Thus:

$ao = new ArrayObject;

get_class($ao); // ArrayObject

What about javascript? How can we do this?

Example:

var f = new FormData();
console.log(/** Qual é o nome da classe de 'f' **/)
  • The question is specific to Formdata or more general?

  • It’s general, @Sergio

2 answers

4


Use the property name, of the object constructor:

var f = new FormData();
console.log(f.constructor.name)
  • 1

    +1. Nice. This one I didn’t know.

0

There is also this little form:

var f = new FormData;
Object.prototype.toString.call(f) // [object FormData]

With the idea of @felipsmartins, this can be done:

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

get_class('uma String'); // "String"
get_class(1); // "Number"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.