tags:

views:

299

answers:

2

How can I check if my javascript object is of a certain type.

var SomeObject = function() { }
var s1 = new SomeObject();

In the case above typeof s1 will return "object". That's not very helpful. Is there some way to check if s1 is of type SomeObject ?

+5  A: 

Yes, using instanceof:

if (s1 instanceof SomeObject) { ... }
T.J. Crowder
I should probably clarify, the link is to MDC because the ECMA spec isn't conveniently linkable (it's a monolithic PDF), but this isn't just a Mozilla thing, it's also in the spec (http://www.ecma-international.org/publications/standards/Ecma-262.htm), Section 11.8.6.
T.J. Crowder
Indeed, it goes back to the earliest JavaScript version in Netscape 2.0. (Another reason not to link to ECMA-262 is that it's staggeringly unclear and unreadable, even by standards-document standards!)
bobince
@bobince: It does take some getting used to the style. :-)
T.J. Crowder
A: 

You could also take a look at the way that they do it in php.js:

http://phpjs.org/functions/get%5Fclass:409

SeanJA