This commit is contained in:
Ilya Kantor 2019-07-31 23:18:20 +03:00
parent 4e9f302982
commit b6adf0b6aa
9 changed files with 51 additions and 106 deletions

View file

@ -1,22 +1,23 @@
# Global object
The global object provides variables and functions that are available anywhere. Mostly, the ones that are built into the language or the environment.
The global object provides variables and functions that are available anywhere. By default, those that are built into the language or the environment.
In a browser it is named `window`, for Node.js it is `global`, for other environments it may have another name.
Recently, `globalThis` was added to the language, as a standartized name for a global object, that should be supported across all environments. In some browsers, namely non-Chromium Edge, `globalThis` is not yet supported, but can be easily polyfilled.
We'll use `window` here, assuming that our environment is a browser. If your script may run in other environments, it's better to use `globalThis` instead.
All properties of the global object can be accessed directly:
```js run
alert("Hello");
// the same as
// is the same as
window.alert("Hello");
```
In a browser, global functions and variables declared with `var` become the property of the global object:
In a browser, global functions and variables declared with `var` (not `let/const`!) become the property of the global object:
```js run untrusted refresh
var gVar = 5;
@ -24,9 +25,9 @@ var gVar = 5;
alert(window.gVar); // 5 (became a property of the global object)
```
Please don't rely on that! This behavior exists for compatibility reasons. Modern scripts use JavaScript modules where such thing doesn't happen. We'll cover them later in the chapter [](info:modules).
Please don't rely on that! This behavior exists for compatibility reasons. Modern scripts use [JavaScript modules](info:modules) where such thing doesn't happen.
Also, more modern variable declarations `let` and `const` do not exhibit such behavior at all:
If we used `let` instead, such thing wouldn't happen:
```js run untrusted refresh
let gLet = 5;
@ -52,7 +53,7 @@ alert(currentUser.name); // John
alert(window.currentUser.name); // John
```
That said, using global variables is generally discouraged. There should be as few global variables as possible. The code design where a function gets "input" variables and produces certain "outcome" is clearer, less prone to errors and easier to test.
That said, using global variables is generally discouraged. There should be as few global variables as possible. The code design where a function gets "input" variables and produces certain "outcome" is clearer, less prone to errors and easier to test than if it uses outer or global variables.
## Using for polyfills