Global Object
An object that constantly exists in the global scope is called a global object. In JavaScript, the global object supplies variables and functions that can be available everywhere.
It is called a window in the browser, global - in Node.js, and can have other names in different environments.
Lately, a standardized name global this was added for the global object. It is meant to be supported by all the environments.
It is possible to access all the properties of the global object directly, as shown below:
console.log("Welcome to Web");
// is the same as
window.console.log("Welcome to Web");
In a browser, global variables and functions that are declared using var (and not const or let), grow into the global object property like this:
<!DOCTYPE html>
<html>
<head> </head>
<body>
<h1> Global object</h1>
<script>
var globalVar = 10;
alert(window.globalVar); // 10 became a property of the global object
</script>
</body>
</html>
But note that modern scripts apply JavaScript modules in which things like that never happen.
A thing like that wouldn’t happen, if let was used instead of var:
<!DOCTYPE html>
<html>
<head> </head>
<body>
<h1> Global object</h1>
<script>
let globalVar = 10;
alert(window.globalVar); // undefined, became a property of the global object
</script>
</body>
</html>
In case a value is very essential, and you want it to be globally available, you should write it as a property directly like this:
//make the current book information global so that all scripts can access it
window.currentBook = {
name: "Javascript"
};
// somewhere else in the code
console.log(currentBook.name); // Javascript
//or if we have a local variable called "currentBook", get it from window explicitly
console.log(window.currentBook.name); //Javascript
So, generally, it is discouraged to use global objects.
Applying Polyfills ¶
As a rule, the global object is implemented to test the support of modern language peculiarities.
For example, let’s check whether there exists a built-in Promise object:
if (!window.Promise) {
console.log("Your browser is old");
}
Actually, it doesn’t exist in old browsers. So if you find out there is none in your browser, then you can make polyfills. In other words, you can insert functions that are not supported by the environment, but the modern standard supports them.
So, in such cases, you can act as follows:
if (!window.Promise) {
window.Promise = ... // custom implementation of the function of the modern
language
}
Summary ¶
In short, we can state that the global object includes variables that are supported anywhere. It involves JavaScript built-ins like Array and environment-specific values.
A generic globalThis name is used for global objects. It is required to store values inside a global object only if they are really global for the project. Moreover, their number should be kept at a minimum.
0 Comments
CAN FEEDBACK
Emoji