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/06-advanced-functions/05-global-object/article.md
+18-18Lines changed: 18 additions & 18 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -81,9 +81,9 @@ window.alert("Hello");
81
81
82
82
К счастью, есть "дорога из ада" — JavaScript модули. Luckily, there's a "road out of hell", called "JavaScript modules".
83
83
84
-
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`.
84
+
Если мы установим тегу `<script>` атрибут `type="module"`, такой скрипт будет считаться отдельным модулем сосбственной областью видимости верхнего уровня (лексическим окружением) не пересекающейся с `window`. 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`.
85
85
86
-
- In a module, `var x` does not become a property of `window`:
86
+
- В модуле `var x` не станет свойством `window`: - In a module, `var x` does not become a property of `window`:
87
87
88
88
```html run
89
89
<script type="module">
@@ -93,7 +93,7 @@ If we set `type="module"` attribute on a `<script>` tag, then such script is con
93
93
</script>
94
94
```
95
95
96
-
- Two modules that do not see variables of each other:
96
+
- Два модуля, которые не видят переменные друг друга: - Two modules that do not see variables of each other:
97
97
98
98
```html run
99
99
<script type="module">
@@ -102,54 +102,54 @@ If we set `type="module"` attribute on a `<script>` tag, then such script is con
102
102
103
103
<script type="module">
104
104
alert(window.x); // undefined
105
-
alert(x); // Error: undeclared variable
105
+
alert(x); //Ошибка: переменная не объявлена Error: undeclared variable
106
106
</script>
107
107
```
108
108
109
-
- And, the last minor thing, the top-level value of `this` in a module is `undefined` (why should it be `window` anyway?):
109
+
- И последнее, в модуле значение `this` на верхнем уровне равно `undefined` (действительно, почему должно быть `window`?): - And, the last minor thing, the top-level value of `this` in a module is `undefined` (why should it be `window` anyway?):
110
110
111
111
```html run
112
112
<script type="module">
113
113
alert(this); // undefined
114
114
</script>
115
115
```
116
116
117
-
**Using `<script type="module">` fixes the design flaw of the language by separating top-level scope from `window`.**
117
+
**Используйте `<script type="module">`, чтобы исправить недостаток проектирования языка, отделяя область видимости верхнего уровня от `window`. Using `<script type="module">` fixes the design flaw of the language by separating top-level scope from `window`.**
118
118
119
-
We'll cover more features of modules later, in the chapter [](info:modules).
119
+
Мы рассмотрим другие свойства модулей позже в главе We'll cover more features of modules later, in the chapter [](info:modules).
120
120
121
-
## Valid uses of the global object
121
+
## Допустимое (правильное?) использование глобального объекта Valid uses of the global object
122
122
123
-
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).
123
+
1. Обычно не рекомендуется использовать глобальные переменные. Желатьльно, применать как можно мешьше таких переменных. Однако, если нужно поместить что-либо в глобальную область видимости, мы можем захотеть добавить это в `window` (или `global` в Node.js) 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).
124
124
125
-
Here we put the information about the current user into a global object, to be accessible from all other scripts:
125
+
Мы помещаем информацию о текущем пользователе в глобальный объект, чтобы она была доступна другим скриптам. Here we put the information about the current user into a global object, to be accessible from all other scripts:
126
126
127
127
```js run
128
-
// explicitly assign it to `window`
128
+
//явное назначение свойства `window` explicitly assign it to `window`
129
129
window.currentUser = {
130
130
name:"John",
131
131
age:30
132
132
};
133
133
134
-
// then, elsewhere, in another script
134
+
//далее, где угодно в другом скрипте then, elsewhere, in another script
135
135
alert(window.currentUser.name); // John
136
136
```
137
137
138
-
2. We can test the global object for support of modern language features.
138
+
2.Мы можем проверить, поддерживает ли глобальный объект современные возможности языка. We can test the global object for support of modern language features.
139
139
140
-
For instance, test if a build-in`Promise` object exists (it doesn't in really old browsers):
140
+
Например, проверить наличие встроенного объекта `Promise` (такая поддержка отсутствует в очень старых браузерах). For instance, test if a build-in`Promise` object exists (it doesn't in really old browsers):
141
141
```js run
142
142
if (!window.Promise) {
143
-
alert("Your browser is really old!");
143
+
alert("Ваш браузер очень старый!"); alert("Your browser is really old!");
144
144
}
145
145
```
146
146
147
-
3. We can create "polyfills": add functions that are not supported by the environment (say, an old browser), but exist in the modern standard.
147
+
3. Мы можем создать полифилл: добавить функции, которые не поддерживаются окружением (скажем, старым браузером), но сущемтвуют в современном стандарте. We can create "polyfills": add functions that are not supported by the environment (say, an old browser), but exist in the modern standard.
148
148
149
149
```js run
150
150
if (!window.Promise) {
151
-
window.Promise = ... // custom implementation of the modern language feature
151
+
window.Promise = ... // собственная реализация современной возможности языка custom implementation of the modern language feature
152
152
}
153
153
```
154
154
155
-
...And of course, if we're in a browser, using `window` to access browser windowfeatures (not as a global object) is completely fine.
155
+
...И конечно, если в браузере мы используем `window` для доступа к функциям окна браузера (не как глобального объекта) это вполне нормально. And of course, if we're in a browser, using `window` to access browser windowfeatures (not as a global object) is completely fine.
0 commit comments