myObject.constructor in ECMAScript 262

A reference to the constructor class for the current object instance.

Property Type

Checking the constructor property for a custom object is a clean way to see its type. The following code takes objects of most any type and returns a string representation of them, suitable for use in source code. Note how the constructor property is used to check the object type of the parameter.

//For more information on this function, see
    var out,tabs='',idre=/^[a-z_][a-z0-9_]*$/i;
    if (!lv) lv=0;
    if (hier) tabs=Math.pow(10,lv).toString().substr(1).replace(/0/g,"\t");
    if (this.constructor==Array){
        for (var i=0,len=this.length;i<len;i++){
        return out+tabs+']';
    }else if(this.constructor==Object){
        for (var key in this){
            if (key!='toSourceCode'){
        return out+tabs+'}';
    }else if(this.constructor==String) return (forObj?'':tabs)+"'"+this+"'";
    else if(this.constructor==Date) return (forObj?'':tabs)+"new Date("+this.valueOf()+")";
    else return (forObj?'':tabs)+this.toString();

The constructor property is especially useful for distinguishing arrays from generic objects, since (per the spec) typeof(myArray) returns the string "object". The following example detects if the returned value is an array or not; if it's not, it is turned into a single-element array.

(In HTML, asking for a form element by name returns the element itself if only one named element exists, or returns an array of elements if more than one name exists. It is often convenient to treat both cases with the same code, which expects an array.)

var myForm=document.getElementById('myFormID');
var products = myForm.elements['product'];
if (products.constructor!=Array) products=[products];

The value of the constructor property is not limited to the built-in object types. The following example shows two custom classes, Mammal and Cat, where a method of the class detects the type of the instance.

function Mammal(name){;
    if (this.constructor==Cat) return "[Cat '""']";
    else return "[Mammal '""']";

function Cat(name){;
Cat.prototype=new Mammal;      //inherit from Mammal
Cat.prototype.constructor=Cat; //but keep the correct constructor

var bob = new Mammal('Bob');
var kitty = new Cat('Felix');

bob.toString();   //returns the string "[Mammal 'Bob']"
kitty.toString(); //returns the string "[Cat 'Felix']"