Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i use constructor.name to detect types in JavaScript

Can I use the "constructor" property to detect types in JavaScript? Or is there something I should know about it.

For example: var a = {}; a.constructor.name; // outputs "Object"

or var b = 1; b.constructor.name; // outputs "Number"

or var d = new Date(); d.constructor.name; // outputs "Date" not Object

or var f = new Function(); f.constructor.name; // outputs "Function" not Object

only if use it on arguments arguments.constructor.name; //outputs Object like first example

I see quite often developers using: Object.prototype.toString.call([]) or

Object.prototype.toString.call({})

like image 449
orustammanapov Avatar asked Aug 12 '11 11:08

orustammanapov


2 Answers

You can use typeof, but it returns misleading results sometimes. Instead, use Object.prototype.toString.call(obj), which uses the object's internal [[Class]] property. You can even make a simple wrapper for it, so it acts similar to typeof:

function TypeOf(obj) {
  return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
}

TypeOf("String") === "string"
TypeOf(new String("String")) === "string"
TypeOf(true) === "boolean"
TypeOf(new Boolean(true)) === "boolean"
TypeOf({}) === "object"
TypeOf(function(){}) === "function"

Don't use obj.constructor because it be changed, although you might be able to use instanceof to see if it is correct:

function CustomObject() {
}
var custom = new CustomObject();
//Check the constructor
custom.constructor === CustomObject
//Now, change the constructor property of the object
custom.constructor = RegExp
//The constructor property of the object is now incorrect
custom.constructor !== CustomObject
//Although instanceof still returns true
custom instanceof CustomObject === true
like image 76
Digital Plane Avatar answered Sep 23 '22 18:09

Digital Plane


You can use typeof Ex: typeof("Hello")

like image 41
Ankur Avatar answered Sep 23 '22 18:09

Ankur