You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 1-js/5-deeper/2-closure/article.md
+49-3Lines changed: 49 additions & 3 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -516,11 +516,57 @@ The features described above make using `var` inconvenient most of time. Because
516
516
517
517
## Global object
518
518
519
-
Most Javascript environments support a so-called "global object".
519
+
A *global object* is the object that provides access to built-in functions and values, defined by the specification and the environment.
520
520
521
-
In browser it is "window", for Node.JS it is "global".
521
+
In a browser it is named "window", for Node.JS it is "global", for other environments it may have another name.
522
+
523
+
So we can call `alert` two ways:
524
+
525
+
```js run
526
+
alert("Hello");
527
+
528
+
// the same as
529
+
window.alert("Hello");
530
+
```
531
+
532
+
Also we can access `Math` as `window.Math`:
533
+
534
+
```js run
535
+
alert( window.Math.min(5,1,4) ); // 1
536
+
```
537
+
538
+
Normally no one does so. Using the global object is generally not a good thing, it's recommended to evade that.
539
+
540
+
**The global object is not a global Lexical Environment.**
541
+
542
+
For historical reasons it also gives access to global Function Declarations and `var` variables, but not `let/const` variables:
543
+
544
+
<!-- can't make runnable in eval, will not work -->
545
+
```js
546
+
var phrase ="Hello";
547
+
let user ="John";
548
+
549
+
functionsayHi() {
550
+
alert(phrase +', '+ user);
551
+
}
552
+
553
+
alert( window.phrase ); // Hello
554
+
alert( window.sayHi ); // function
555
+
556
+
*!*
557
+
alert( window.user ); // undefined
558
+
*/!*
559
+
```
560
+
561
+
In the example above you can clearly see that `let user` is not in `window`.
562
+
563
+
That's because the idea of a global object as a way to access "all global things" comes from ancient times. In modern scripts its use is not recommended, and modern language features like `let/const` do not make friends with it.
564
+
565
+
566
+
TODO
567
+
568
+
As said ed in the [specification](https://tc39.github.io/ecma262/#sec-lexical-environments), the global object provides access to *some* global variables.
522
569
523
-
As described in the [specification](https://tc39.github.io/ecma262/#sec-lexical-environments), the global object provides access to *some* global variables.
0 commit comments