May 12, 2010

How to tell type of an object in javascript

We can use typeof, instanceof, and constructor to tell type of an object. But they have different effect. The "typeof" operator will return "object" for all custom types . "instanceof" will return true, if the object's constructor is in the list of constructor hierarchy. "constructor" will return the top constructor in the constructor hierarchy. Below is some test code

function Person() {}
function Developer(){}
Developer.prototype = new Person();

var dev = new Developer();

assert( typeof dev == "object");
assert( dev instanceof Developer);
assert( dev instanceof Person);
assert( dev.constructor == Person);
assert( dev.constructor != Developer);