Reputation: 31
I am working in JavaScript where I need to check the instanceof
a custom JavaScript object & if the instance of that object is customTypeA then I need perform certain functions, where as in all other cases, we need to perform some different set of logic.
More detailed scenario:
We have generic form submit button which gets included on all form pages. Now we have a common JavaScript for form submit and specific JavaScript files for each form pages. Each of these specific JavaScript files create an object with name of commonObjectName
. Where on form submit JavaScript calls validate & submit on commonObjectName
, which will in turn invoke validate & submit for the respective JavaScript instance.
Now, when I need to perform certain checks between validate & submit actions for form A, where as they are not needed for form B, so I wrote below code in formSubmit.js
var commonObjInstanceOfFormA = commonObjectName instanceof FormAJavascript;
if(commonObjInstanceOffFormA) {
//do something
} else {
//do something else
}
Now, the problem occurs when I am on Form B. FormAJavascript
type gives a reference error since it is not included on form B at all.
Is there a way to find the type of contructor of commonObjectName
in a string format or find the instance of the object in efficient way so that I can perform a different set of logic for type A & different for Type B?
Upvotes: 3
Views: 112
Reputation: 31
Finally I ended up using my form page id to confirm which form this is, I am trying to get formId in javascript & asserting it against string 'formA'. If assertion succeeds, then it means it is form A.
I would still like to have an elegant way of finding the form, instead of checking for form id on every single form. But atleast this works.
Upvotes: 0
Reputation: 175748
Declare any types you subsequently want to test against whilst preserving them if they exist:
var FormAJavascript = FormAJavascript || null;
Test with:
if (FormAJavascript != null && commonObjectName instanceof FormAJavascript)
Upvotes: 0
Reputation: 61351
Why not check for it with good old typeof commonObjectName != 'undefined'
? It will do the check first and only if it succeeds in finding commonObjectName
it will then try to match it by type, then repeat same for objectB on formB.
var commonObjInstanceOfFormA = typeof commonObjectName != 'undefined' && commonObjectName instanceof FormAJavascript;
var commonObjInstanceOfFormB = typeof commonObjectName != 'undefined' && commonObjectName instanceof FormBJavascript;
if(commonObjInstanceOffFormA) {
//do something
} else {
//do something else
}
Upvotes: 1