Skip to content

Commit e002be4

Browse files
committed
up
1 parent d9a1e9b commit e002be4

File tree

1 file changed

+49
-3
lines changed

1 file changed

+49
-3
lines changed

1-js/5-deeper/2-closure/article.md

Lines changed: 49 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -516,11 +516,57 @@ The features described above make using `var` inconvenient most of time. Because
516516

517517
## Global object
518518

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.
520520

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+
function sayHi() {
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.
522569

523-
As described in the [specification](https://tc39.github.io/ecma262/#sec-lexical-environments), the global object provides access to *some* global variables.
524570

525571
The key word here is "some". In practice:
526572

0 commit comments

Comments
 (0)