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 ?
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.
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.
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.
Yes, using instanceof
(MDN link | spec link):
if (s1 instanceof SomeObject) { ... }
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With