Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript type of custom object

Tags:

javascript

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 ?

like image 324
BjartN Avatar asked Sep 28 '09 10:09

BjartN


People also ask

What are custom object types?

Custom object types must be created in a stage instance, then replicated to production. For example, you could create an object type of 'Sample'. You create the custom object type 'Sample' and then give it attributes, for instance, 'SKU' and 'Date.

What is custom objects in JavaScript?

All JavaScript coders eventually reach a stage where they would like to create and use their own objects, apart from the pre-built ones, such as document or Math. Custom objects allow you to build up your own personal JavaScript "toolbox" that extends beyond what the pre-build objects have to offer.

What is typeof object in JavaScript?

typeof is a JavaScript keyword that will return the type of a variable when you call it. You can use this to validate function parameters or check if variables are defined. There are other uses as well.


2 Answers

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

if (s1 instanceof SomeObject) { ... } 
like image 158
T.J. Crowder Avatar answered Sep 22 '22 10:09

T.J. Crowder


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)

like image 25
AAron Avatar answered Sep 18 '22 10:09

AAron