When and why to use window before functions?

Asked

Viewed 200 times

9

There are numerous predefined Javascript functions that can be used with or without the object window as prefix. Example:

window.setTimeout(function() {

});

setTimeout(function() {

});

What is the rule for using this object before the functions? And what is the recommended way to work with it?

1 answer

7


Javascript native functions (from the Browser) are part of the Object window and are global. This is the same as saying that the properties of window are accessible in the global scope. That is, they can be used in any scope.

However, they may be overwritten, and therefore no longer available within a certain scope/function. For example:

console.log(window.location.hostname); // pt.stackoverflow.com
(function () {
    var location = {};
    location.hostname= 'fooooo';
    console.log(location.hostname); // fooooo
    console.log(window.location.hostname); // pt.stackoverflow.com
})();

in this case window.location.pathname will access the property location of window. But if, within another scope, we declare a name variable pathname then in that scope, pathname will not be the same as window.pathname.

So, if necessary we can always access the "original" via window. The reason not to use window.pathname always is to save characters basically.

  • "superscripts" is not a good term. In English it is said shadowed, but I don’t know what would be a good translation. Maybe "superimposed" or something along those lines.

  • In this case, it is correct to state that the object window is immutable?

  • @Kazzkiq not. The properties of window can also be overwritten. Example: http://jsfiddle.net/pz3eazpv/

  • But the window itself can’t, right? (e.g..: window = 1)

  • 1

    @bfavaretto in European Portuguese superimposed gives idea that the other is still under. I wrote over as who says write over. But maybe none of them are good for Brazil and Europe :P

  • But isn’t that right? The other one is still below, in the scope more outside (in this case, the global).

  • @Exact Kazzkiq. In case you want to recover overwritten native functions, you can create an iframe and get "this window" what you need.

  • @Kazzkiq You can’t overwrite the whole object there. For curiosity, see http://answall.com/q/2427/74

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.