7

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({})

orustammanapov
  • 1,792
  • 5
  • 25
  • 44

2 Answers2

7

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
Community
  • 1
  • 1
Digital Plane
  • 37,354
  • 7
  • 57
  • 59
1

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

Ankur
  • 33,367
  • 2
  • 46
  • 72
  • typeof won´t actually so precise because `alert ( typeof new Number() ) // Object` – veidelis Aug 12 '11 at 11:18
  • Agree, because JavaScript is not a typed language you cannt expect its typeof to be precise :) – Ankur Aug 12 '11 at 11:20
  • 1
    No, JavaScript is a loosely typed language. – veidelis Aug 12 '11 at 11:24
  • Are you sure??? `typeof` opertaor is the best choise to find out is the variable istantiated or not(or is is it exists, there are some issues too) but if i have something like that: `var a = function() {}; var b = new a(); typeof a; //outputs object` or `typeof new Array(); //outputs object`. so how can i use to make it precisely? – orustammanapov Aug 12 '11 at 11:35