I've seen lots of people using window.
when calling some variable. But aren't all the variables of a same window actually in window
?
wi开发者_StackOverflow社区ndow.onorientationchange = function() {
var orientation = window.orientation; // <-- WHY?
switch(orientation) {
/* ... */
}
}
But the same people use alert()
, document
, etc. So why?
At certain times you want to expose only certain functions/variables to be explicit properties of the window
.
(function() {
var jQuery = function(selector) { alert( selector ) }
})();
jQuery // not defined
If we alter it to be:
(function() {
var jQuery = function(selector) { alert( selector ) }
window.jQuery = jQuery;
})();
then we "expose" it from a private namespace explicitly.
And yes, you do not have to explicitly declare window.
to invoke methods such as alert
, but everyone has their own style of coding and everyone has their own degree of how explicit their statements should be.
Some people explicitly prefix window.
to global methods such as alert
in order to avoid any confusion. Let's say you defined a function in a private namespace that was named alert
, for example...
(function() {
function alert() {}
alert('lol'); // does nothing
window.alert('lol') // does something
})();
We cannot use alert
inside of that private namespace to do our alerting, since we defined a function with exactly the same name. We have to explicitly reference the window.alert
method to get around that.
But for general purposes, I would say it's perfectly fine to not prefix things with window.
unless you are exposing things in a private namespace to the global namespace. So please use document
and alert
and such as is, in your code.
In many javascript tutorials alert(), document() and so on are used without fully qualified window object and I think they just repeat that code.
精彩评论