When and why to use window before functions?

9

There are a number of predefined functions in JavaScript that can be used with or without the window object as a prefix. Example:

window.setTimeout(function() {

});

setTimeout(function() {

});

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

    
asked by anonymous 14.09.2015 / 20:29

1 answer

7

The native functions in JavaScript (of the Browser) are part of the Object window and are global. This is to say that the properties of window are accessible in the global scope. That is, they can be used in any scope.

However, they can 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 variable of name pathname then in that scope, pathname will not be the same as window.pathname .

Then if necessary we can always access the "original" via window . The reason for not using window.pathname is always to save characters basically.

    
14.09.2015 / 20:48