refactor promise, geneerators, global object
This commit is contained in:
parent
be9c5a7b5f
commit
2ee2751216
69 changed files with 900 additions and 643 deletions
|
@ -1,171 +1,155 @@
|
|||
|
||||
|
||||
# Global object
|
||||
|
||||
When JavaScript was created, there was an idea of a "global object" that provides all global variables and functions. It was planned that multiple in-browser scripts would use that single global object and share variables through it.
|
||||
|
||||
Since then, JavaScript greatly evolved, and that idea of linking code through global variables became much less appealing. In modern JavaScript, the concept of modules took its place.
|
||||
|
||||
But the global object still remains in the specification.
|
||||
The global object provides variables and functions that are available anywhere. Mostly, the ones that are built into the language or the host environment.
|
||||
|
||||
In a browser it is named "window", for Node.JS it is "global", for other environments it may have another name.
|
||||
|
||||
It does two things:
|
||||
For instance, we can call `alert` as a method of `window`:
|
||||
|
||||
1. Provides access to built-in functions and values, defined by the specification and the environment.
|
||||
For instance, we can call `alert` directly or as a method of `window`:
|
||||
```js run
|
||||
alert("Hello");
|
||||
|
||||
```js run
|
||||
alert("Hello");
|
||||
|
||||
// the same as
|
||||
window.alert("Hello");
|
||||
```
|
||||
|
||||
The same applies to other built-ins. E.g. we can use `window.Array` instead of `Array`.
|
||||
|
||||
2. Provides access to global Function Declarations and `var` variables. We can read and write them using its properties, for instance:
|
||||
|
||||
<!-- no-strict to move variables out of eval -->
|
||||
```js untrusted run no-strict refresh
|
||||
var phrase = "Hello";
|
||||
|
||||
function sayHi() {
|
||||
alert(phrase);
|
||||
}
|
||||
|
||||
// can read from window
|
||||
alert( window.phrase ); // Hello (global var)
|
||||
alert( window.sayHi ); // function (global function declaration)
|
||||
|
||||
// can write to window (creates a new global variable)
|
||||
window.test = 5;
|
||||
|
||||
alert(test); // 5
|
||||
```
|
||||
|
||||
...But the global object does not have variables declared with `let/const`!
|
||||
|
||||
```js untrusted run no-strict refresh
|
||||
*!*let*/!* user = "John";
|
||||
alert(user); // John
|
||||
|
||||
alert(window.user); // undefined, don't have let
|
||||
alert("user" in window); // false
|
||||
// the same as
|
||||
window.alert("Hello");
|
||||
```
|
||||
|
||||
```smart header="The global object is not a global Environment Record"
|
||||
In versions of ECMAScript prior to ES-2015, there were no `let/const` variables, only `var`. And global object was used as a global Environment Record (wordings were a bit different, but that's the gist).
|
||||
We can reference other built-in functions like `Array` as `window.Array` and create our own properties on it.
|
||||
|
||||
But starting from ES-2015, these entities are split apart. There's a global Lexical Environment with its Environment Record. And there's a global object that provides *some* of the global variables.
|
||||
## Browser: the "window" object
|
||||
|
||||
As a practical difference, global `let/const` variables are definitively properties of the global Environment Record, but they do not exist in the global object.
|
||||
For historical reasons, in-browser `window` object is a bit messed up.
|
||||
|
||||
Naturally, that's because the idea of a global object as a way to access "all global things" comes from ancient times. Nowadays it's not considered to be a good thing. Modern language features like `let/const` do not make friends with it, but old ones are still compatible.
|
||||
```
|
||||
1. It provides the "browser window" functionality, besides playing the role of a global object.
|
||||
|
||||
## Uses of "window"
|
||||
|
||||
In server-side environments like Node.JS, the `global` object is used exceptionally rarely. Probably it would be fair to say "never".
|
||||
|
||||
In-browser `window` is sometimes used though.
|
||||
|
||||
Usually, it's not a good idea to use it, but here are some examples you can meet.
|
||||
|
||||
1. To access exactly the global variable if the function has the local one with the same name.
|
||||
|
||||
```js untrusted run no-strict refresh
|
||||
var user = "Global";
|
||||
|
||||
function sayHi() {
|
||||
var user = "Local";
|
||||
|
||||
*!*
|
||||
alert(window.user); // Global
|
||||
*/!*
|
||||
}
|
||||
|
||||
sayHi();
|
||||
```
|
||||
|
||||
Such use is a workaround. Would be better to name variables differently, that won't require use to write the code it this way. And please note `"var"` before `user`. The trick doesn't work with `let` variables.
|
||||
|
||||
2. To check if a certain global variable or a builtin exists.
|
||||
|
||||
For instance, we want to check whether a global function `XMLHttpRequest` exists.
|
||||
|
||||
We can't write `if (XMLHttpRequest)`, because if there's no `XMLHttpRequest`, there will be an error (variable not defined).
|
||||
|
||||
But we can read it from `window.XMLHttpRequest`:
|
||||
We can use `window` to access properties and methods, specific to the browser window:
|
||||
|
||||
```js run
|
||||
if (window.XMLHttpRequest) {
|
||||
alert('XMLHttpRequest exists!')
|
||||
}
|
||||
alert(window.innerHeight); // shows the browser window height
|
||||
|
||||
window.open('http://google.com'); // opens a new browser window
|
||||
```
|
||||
|
||||
If there is no such global function then `window.XMLHttpRequest` is just a non-existing object property. That's `undefined`, no error, so it works.
|
||||
2. Top-level `var` variables and function declarations automatically become properties of `window`.
|
||||
|
||||
We can also write the test without `window`:
|
||||
For instance:
|
||||
```js untrusted run no-strict refresh
|
||||
var x = 5;
|
||||
|
||||
```js
|
||||
if (typeof XMLHttpRequest == 'function') {
|
||||
/* is there a function XMLHttpRequest? */
|
||||
}
|
||||
alert(window.x); // 5 (var x becomes a property of window)
|
||||
|
||||
window.x = 0;
|
||||
|
||||
alert(x); // 0, variable modified
|
||||
```
|
||||
|
||||
This doesn't use `window`, but is (theoretically) less reliable, because `typeof` may use a local XMLHttpRequest, and we want the global one.
|
||||
Please note, that doesn't happen with more modern `let/const` declarations:
|
||||
|
||||
```js untrusted run no-strict refresh
|
||||
let x = 5;
|
||||
|
||||
3. To take the variable from the right window. That's probably the most valid use case.
|
||||
alert(window.x); // undefined ("let" doesn't create a window property)
|
||||
```
|
||||
|
||||
A browser may open multiple windows and tabs. A window may also embed another one in `<iframe>`. Every browser window has its own `window` object and global variables. JavaScript allows windows that come from the same site (same protocol, host, port) to access variables from each other.
|
||||
3. Also, all scripts share the same global scope, so variables declared in one `<script>` become visible in another ones:
|
||||
|
||||
That use is a little bit beyond our scope for now, but it looks like:
|
||||
```html run
|
||||
<iframe src="/" id="iframe"></iframe>
|
||||
<script>
|
||||
var a = 1;
|
||||
let b = 2;
|
||||
</script>
|
||||
|
||||
<script>
|
||||
alert( innerWidth ); // get innerWidth property of the current window (browser only)
|
||||
alert( Array ); // get Array of the current window (javascript core builtin)
|
||||
|
||||
// when the iframe loads...
|
||||
iframe.onload = function() {
|
||||
// get width of the iframe window
|
||||
*!*
|
||||
alert( iframe.contentWindow.innerWidth );
|
||||
*/!*
|
||||
// get the builtin Array from the iframe window
|
||||
*!*
|
||||
alert( iframe.contentWindow.Array );
|
||||
*/!*
|
||||
};
|
||||
alert(a); // 1
|
||||
alert(b); // 2
|
||||
</script>
|
||||
```
|
||||
|
||||
Here, first two alerts use the current window, and the latter two take variables from `iframe` window. Can be any variables if `iframe` originates from the same protocol/host/port.
|
||||
4. And, a minor thing, but still: the value of `this` in the global scope is `window`.
|
||||
|
||||
## "this" and global object
|
||||
```js untrusted run no-strict refresh
|
||||
alert(this); // window
|
||||
```
|
||||
|
||||
Sometimes, the value of `this` is exactly the global object. That's rarely used, but some scripts rely on that.
|
||||
Why was it made like this? At the time of the language creation, the idea to merge multiple aspects into a single `window` object was to "make things simple". But since then many things changed. Tiny scripts became big applications that require proper architecture.
|
||||
|
||||
1. In the browser, the value of `this` in the global area is `window`:
|
||||
Is it good that different scripts (possibly from different sources) see variables of each other?
|
||||
|
||||
No, it's not, because it may lead to naming conflicts: the same variable name can be used in two scripts for different purposes, so they will conflict with each other.
|
||||
|
||||
As of now, the multi-purpose `window` is considered a design mistake in the language.
|
||||
|
||||
Luckily, there's a "road out of hell", called "Javascript modules".
|
||||
|
||||
If we set `type="module"` attribute on a `<script>` tag, then such script is considered a separate "module" with its own top-level scope (lexical environment), not interfering with `window`.
|
||||
|
||||
- In a module, `var x` does not become a property of `window`:
|
||||
|
||||
```html run
|
||||
<script type="module">
|
||||
var x = 5;
|
||||
|
||||
alert(window.x); // undefined
|
||||
</script>
|
||||
```
|
||||
|
||||
- Two modules that do not see variables of each other:
|
||||
|
||||
```html run
|
||||
<script type="module">
|
||||
let x = 5;
|
||||
</script>
|
||||
|
||||
<script type="module">
|
||||
alert(window.x); // undefined
|
||||
alert(x); // Error: undeclared variable
|
||||
</script>
|
||||
```
|
||||
|
||||
- And, the last minor thing, the top-level value of `this` in a module is `undefined` (why should it be `window` anyway?):
|
||||
|
||||
```html run
|
||||
<script type="module">
|
||||
alert(this); // undefined
|
||||
</script>
|
||||
```
|
||||
|
||||
**Using `<script type="module">` fixes the design flaw of the language by separating top-level scope from `window`.**
|
||||
|
||||
We'll cover more features of modules later, in the chapter [](info:modules).
|
||||
|
||||
## Valid uses of the global object
|
||||
|
||||
1. Using global variables is generally discouraged. There should be as few global variables as possible, but if we need to make something globally visible, we may want to put it into `window` (or `global` in Node.js).
|
||||
|
||||
Here we put the information about the current user into a global object, to be accessible from all other scripts:
|
||||
|
||||
```js run
|
||||
// outside of functions
|
||||
alert( this === window ); // true
|
||||
// explicitly assign it to `window`
|
||||
window.currentUser = {
|
||||
name: "John",
|
||||
age: 30
|
||||
};
|
||||
|
||||
// then, elsewhere, in another script
|
||||
alert(window.currentUser.name); // John
|
||||
```
|
||||
|
||||
Other, non-browser environments, may use another value for `this` in such cases.
|
||||
2. We can test the global object for support of modern language features.
|
||||
|
||||
2. When a function with `this` is called in non-strict mode, it gets the global object as `this`:
|
||||
```js run no-strict
|
||||
// not in strict mode (!)
|
||||
function f() {
|
||||
alert(this); // [object Window]
|
||||
For instance, test if a build-in `Promise` object exists (it doesn't in really old browsers):
|
||||
```js run
|
||||
if (!window.Promise) {
|
||||
alert("Your browser is really old!");
|
||||
}
|
||||
|
||||
f(); // called without an object
|
||||
```
|
||||
|
||||
By specification, `this` in this case must be the global object, even in non-browser environments like Node.JS. That's for compatibility with old scripts, in strict mode `this` would be `undefined`.
|
||||
3. We can create "polyfills": add functions that are not supported by the environment (say, an old browser), but exist in the modern standard.
|
||||
|
||||
```js run
|
||||
if (!window.Promise) {
|
||||
window.Promise = ... // custom implementation of the modern language feature
|
||||
}
|
||||
```
|
||||
|
||||
...And of course, if we're in a browser, using `window` to access browser window features (not as a global object) is completely fine.
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue