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 browserwindow
object. Is there something inwindow
that I can check if it is really the browserwindow
object?And how to check if the browser
window
object actually exists and not just somewindow
variable containing an object.Suppose you can't tell if
someVar
iswindow
by itself, and you want to match it against the real browserwindow
object likesomeVar === window
, how do you getwindow
that you are sure it is the browserwindow
and not some other object from an outer scope namedwindow
, or some other global from another environment?
Just to clarify a bit more:
- I'm not looking for the global of the environment. I'm looking for the browser
window
object specifically. - I'm not checking if the script is running on the browser.
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.