Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check the class of an instance in Javascript? [duplicate]

Tags:

javascript

Possible Duplicate:
How to get a JavaScript Object's Class?

In Ruby I could do this to check the class of an instance:

'this is an string'.class

=>String

Is there any similar thing in js?

like image 255
mko Avatar asked Sep 02 '25 06:09

mko


1 Answers

You probably mean type or constructor, not class. Class has a different meaning in JavaScript.

To get the class:

var getClassOf = Function.prototype.call.bind(Object.prototype.toString);
getClassOf(new Date());     // => "[object Date]"
getClassOf('test string');  // => "[object String]"
getClassOf({ x: 1 });       // => "[object Object]"
getClassOf(function() { }); // => "[object Function]"

See this related MDN article.

To get the constructor or prototype there are several ways, depending on what you need.

To discover what type of primitive you have, use typeof. This is the best thing to use with strings, booleans, numbers, etc:

typeof 'test string';  // => 'string'
typeof 3;              // => 'number'
typeof false;          // => 'boolean'
typeof function() { }; // => 'function'
typeof { x: 1 };       // => 'object'
typeof undefined;      // => 'undefined'

Just beware that null acts weird in this case, as typeof null will give you "object", not "null".

You can also get the prototype, the backbone JavaScript inheritance, with Object.getPrototypeOf(myObject) (or myObject.__proto__ or myObject.constructor.prototype in some browsers when getPrototypeOf isn't supported).

You can test the constructor with instanceof:

new Date() instanceof Date;  // => true

You can also reasonably get the constructor with myObject.constructor, although be aware that this can be changed. To get the name of the constructor, use myObject.constructor.name.

new Date().constructor.name;   // => 'Date'
like image 94
Nathan Wall Avatar answered Sep 04 '25 21:09

Nathan Wall