Saturday, May 25, 2024
 Popular · Latest · Hot · Upcoming
110
rated 0 times [  113] [ 3]  / answers: 1 / hits: 55977  / 12 Years ago, sat, august 18, 2012, 12:00:00

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?


More From » javascript

 Answers
8

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'

[#83560] Friday, August 17, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
elliem

Total Points: 415
Total Questions: 117
Total Answers: 94

Location: American Samoa
Member since Fri, Aug 26, 2022
2 Years ago
;