Given that my plugin could be run on any JS engine (in a browser or not),
How does one know that some variable is actually the browser window object.
Like how do I know if someVar references the browser window object. Is there something in window that I can check if it is really the browser window object?
And how to check if the browser window object actually exists and not just some window variable containing an object.
Suppose you can't tell if someVar is window by itself, and you want to match it against the real browser window object like someVar === window, how do you get window that you are sure it is the browser window and not some other object from an outer scope named window, or some other global from another environment?
Just to clarify a bit more:
window object specifically.I can't do something like if(!window) since window could just be another object declared somewhere outside the scope.
function someFunction(){
var window = {foo:'bar'};
(function(){
console.log(window); //{foo:'bar'}
}());
}
I can't check if(window.window === window) since I can also do self referencing, and like said earlier, window could be an object from an outer scope:
var bar = {};
bar.bar = bar;
bar.bar.bar.bar.bar.bar === bar; //true
And the following may not work since the script could be wrapped or concatenated within something other than the global space. this could also be modified with calls like call(), apply() or bind().
//Stand-alone, I can assume window is global since "this" is the global in global space
(function(window){
//window may not be window
}(this));
//But when this happens
someNamespace.someFunction = function(){
(function(window){
//window may not be window
}(this));
}
//or this:
someNamespace.someFunction.call({});
I have a feeling that this is a duplicate, but I couldn't find where I first saw it.
This will not only test for current window, but for window in general:
if (window.toString() === "[object Window]") {
// your code here
}
[edit]
toString() object prototype was available from JavaScript initial version 1.0 and was an old fashioned way to check for the "class". As well as the method mentioned in another answer to this question - to check for the unique object propert, which is faster to execute than string comparison.
Since JavaScript 1.4 (ECMAScript 3rd edition 1999) we are able to utilize instanceof operator to check for the object Class which is the right method for this task.
if (window instanceof Window) {
// your code here
}
You can get the global object like so...
var global = (1,eval)("this");
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