If you happen to be using ECMA 6, (Like on NodeJS, or Newer browser tech) you can use the following function to get 'class name'.
// primitives
var array = [], obj = {}, str = "", date = new Date(),
num = 1, flt = 1.0, reg = new RegExp(/woohoo/g),
bool = true, myType = new MyType(), udf = undefined, nul = null;
// names of various types (primitive and not)
var names = cName(array) + ", " + cName(obj) + ", " + cName(str) + ", " +
cName(num) + ", " + cName(flt) + ", " + cName(reg) + ", " +
cName(bool) + ", " + cName(date) + ", " + cName(myType) + ", " +
cName(MyType) + ", " + cName(udf) + ", " + cName(nul);
// custom type
function MyType(){}
console.log( names );
// output:
// Array, Object, String, Number, Number, RegExp, Boolean, Date, MyType, MyType, undefined, null
// implementation
function cName(obj){
// default to non-null value.
var ret = '';
if(typeof obj === 'undefined') { ret = 'undefined'; }
else if(obj === null) { ret = String(obj); }
else if(typeof obj.constructor !== 'undefined' && obj.constructor !== null){
ret = obj.constructor.name
if(ret == 'Function') { ret = obj.name; }
}
return ret;
}
Although there really are no 'classes', this helps when being passed something like Array, vs Object, vs. Null
and you want to know which one it is.
calling typeof
on any of those will return 'object'
. Then there is the the caveat of having to deal with things like null
and undefined
.
Calling Object.prototype.toString()
is heavier than accessing constructor.name
as there is no conversion from some type to a string, and I believe the constructor
and constructor.name
are both member variables, not a getter
, which means no additional functions are called in retrieving said name.