Javascript type of custom object

Whatever you do, avoid obj.constructor.name or any string version of the constructor. That works great until you uglify/minify your code, then it all breaks since the constructor gets renamed to something obscure (ex: 'n') and your code will still do this and never match:

// Note: when uglified, the constructor may be renamed to 'n' (or whatever),
// which breaks this code since the strings are left alone.
if (obj.constructor.name === 'SomeObject') {}

Note:

// Even if uglified/minified, this will work since SomeObject will
// universally be changed to something like 'n'.
if (obj instanceof SomeObject) {}

(BTW, I need higher reputation to comment on the other worthy answers here)


Yes, using instanceof (MDN link | spec link):

if (s1 instanceof SomeObject) { ... }

Tags:

Javascript