Question on how to check for the existence of an object:
I have a situation where I need to check if a JS variable has been set in the page. I wrote a function to check for the validity of an object, but I ran into several issues while trying to check for the existence of an object. To understand how to check for the existence of an object, a ran of the following script in the body of the HTML page. Basically, it checks for the existence of variable “z” which does not exist and is not declared in the page. I commented in and out each line that defines the “ans” variable and recorded the result for that line after the “–>”. I also labeled each line as “v1”, “v2”, and so on.
var isValidObj = (function(objToTest){
if (typeof objToTest === undefined) {
return false;
}
if (objToTest === null) {
return false;
}
return true;
});
//var ans = isValidObj(z); // v1 --> throws error
//var ans = isValidObj(window.z); // v2 --> true
//var ans = (z === undefined); // v3 --> throws error
//var ans = (z); // v4 --> throws error
//var ans = (window.z === undefined); // v5 --> true
//var ans = (window.z); // v6 --> undefined
//var ans = (typeof z === 'undefined'); // v7 --> true
alert(ans);
I think I understand the results of each line except for v1, v3, and v4. I don’t understand why these throwing error specially since “window.z” works just fine. Shouldn’t saying “z” in your code be the same as saying “window.z”. Isn’t the window object assumed? Does this mean that each time I check for an objects existence I need to use the fully qualified name of “window.TheObjectImChecking”? It is also puzzling to me why v7 works but nothing else can refer to z directly.
Thanks in advance…