Skip to content

Commit 562bbd9

Browse files
committed
merge
2 parents 56a826e + 728998b commit 562bbd9

File tree

6 files changed

+39
-24
lines changed

6 files changed

+39
-24
lines changed

1-js/02-first-steps/03-strict-mode/article.md

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,9 +53,17 @@ alert("some code");
5353
5454
Иногда, когда `use strict` имеет значение, вы можете получить неправильные результаты.
5555
56-
Даже если мы нажмём `key:Shift+Enter` для ввода нескольких строк и напишем вверху `use strict` -- это не сработает. Это связано с тем, как консоль выполняет код внутри.
56+
Можно использовать `key:Shift+Enter` для ввода нескольких строк и написать вверху `use strict`:
5757
58-
Надёжный способ сделать так, чтобы `use strict` заработал, это ввести код в консоль следующим образом:
58+
```js
59+
'use strict'; <Shift+Enter для перехода на новую строку>
60+
// ...ваш код...
61+
<Enter для запуска>
62+
```
63+
64+
В большинстве браузеров, включая Chrome и Firefox, это работает.
65+
66+
В старых браузерах консоль не учитывает такой `use strict`, там можно "оборачивать" код в функцию, вот так:
5967

6068
```js
6169
(function() {

1-js/06-advanced-functions/11-currying-partials/article.md

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,7 @@ function curry(f) {
169169

170170
Продвинутое каррирование позволяет вызывать функцию, как обычно, так и с частичным применением.
171171

172-
Например, у нас есть функция логирования `log(date, importance, message)`, которая форматирует и выводит информацию. В реальных проектах у таких функций есть много других полезных возможностей, например, посылать логи по сети:
172+
Например, у нас есть функция логирования `log(date, importance, message)`, которая форматирует и выводит информацию. В реальных проектах у таких функций есть много других полезных возможностей, например, посылать логи по сети, здесь для простоты используем `alert`:
173173

174174
```js
175175
function log(date, importance, message) {
@@ -192,25 +192,26 @@ log(new Date(), "DEBUG", "some debug");
192192
...Но также работает вариант с каррированием:
193193

194194
```js
195+
log(new Date(), "DEBUG", "some debug"); // log(a,b,c)
195196
log(new Date())("DEBUG")("some debug"); // log(a)(b)(c)
196197
```
197198

198199
Давайте сделаем удобную функцию для логов с текущим временем:
199200

200201
```js
201202
// todayLog будет частичным применением функции log с фиксированным первым аргументом
202-
let todayLog = log(new Date());
203+
let logNow = log(new Date());
203204

204205
// используем её
205-
todayLog("INFO", "message"); // [HH:mm] INFO message
206+
logNow("INFO", "message"); // [HH:mm] INFO message
206207
```
207208

208209
А теперь удобная функция для логов отладки с текущим временем:
209210

210211
```js
211-
let todayDebug = todayLog("DEBUG");
212+
let debugNow = logNow("DEBUG");
212213

213-
todayDebug("message"); // [HH:mm] DEBUG message
214+
debugNow("message"); // [HH:mm] DEBUG message
214215
```
215216

216217
Итак:

2-ui/1-document/08-styles-and-classes/article.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -66,10 +66,10 @@ So we can operate both on the full class string using `className` or on individu
6666
Methods of `classList`:
6767

6868
- `elem.classList.add/remove("class")` -- adds/removes the class.
69-
- `elem.classList.toggle("class")` -- if the class exists, then removes it, otherwise adds it.
69+
- `elem.classList.toggle("class")` -- adds the class if it doesn't exist, otherwise removes it.
7070
- `elem.classList.contains("class")` -- returns `true/false`, checks for the given class.
7171

72-
Besides that, `classList` is iterable, so we can list all classes like this:
72+
Besides, `classList` is iterable, so we can list all classes with `for..of`, like this:
7373

7474
```html run
7575
<body class="main page">
@@ -147,7 +147,7 @@ To set the full style as a string, there's a special property `style.cssText`:
147147
</script>
148148
```
149149

150-
We rarely use it, because such assignment removes all existing styles: it does not add, but replaces them. May occasionally delete something needed. But still can be done for new elements when we know we won't delete something important.
150+
This property is rarely used, because such assignment removes all existing styles: it does not add, but replaces them. May occasionally delete something needed. But we can safely use it for new elements, when we know we won't delete an existing style.
151151

152152
The same can be accomplished by setting an attribute: `div.setAttribute('style', 'color: red...')`.
153153
````

2-ui/5-loading/02-script-async-defer/article.md

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -188,11 +188,13 @@ loadScript("/article/script-async-defer/small.js");
188188
| `defer` | *Порядок документа* (как расположены в документе). | Выполняется после того, как документ загружен и обработан (ждёт), непосредственно перед `DOMContentLoaded`. |
189189

190190
```warn header="Страница без скриптов должна быть рабочей"
191-
Пожалуйста, помните, что когда вы используете `defer`, страница видна до того, как скрипт загрузится и подключит все графические компоненты.
191+
Пожалуйста, помните, что когда вы используете `defer`, страница видна до того, как скрипт загрузится.
192192
193-
Поэтому кнопки должны быть отключены с помощью CSS или другим образом.
193+
Пользователь может знакомиться с содержимым страницы, читать её, но графические компоненты пока отключены.
194194
195-
На практике `defer` используется для скриптов, которым требуется доступ ко всему DOM и/или важен их относительный порядок выполнения.
195+
Поэтому обязательно должна быть индикация загрузки, нерабочие кнопки - отключены с помощью CSS или другим образом. Чтобы пользователь явно видел, что уже готово, а что пока нет.
196+
```
196197

198+
На практике `defer` используется для скриптов, которым требуется доступ ко всему DOM и/или важен их относительный порядок выполнения.
197199

198-
А `async` используется для независимых скриптов, например счётчиков и рекламы, относительный порядок выполнения которых не играет роли.
200+
А `async` хорош для независимых скриптов, например счётчиков и рекламы, относительный порядок выполнения которых не играет роли.

6-data-storage/03-indexeddb/article.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -154,8 +154,8 @@ let openRequest = indexedDB.open("db", 1);
154154
// создаём хранилище объектов для books, если ешё не существует
155155
openRequest.onupgradeneeded = function() {
156156
let db = openRequest.result;
157-
if (!db.objectStoreNames.contains('books')) {
158-
db.createObjectStore('books', {keyPath: 'id'});
157+
if (!db.objectStoreNames.contains('books')) { // if there's no "books" store
158+
db.createObjectStore('books', {keyPath: 'id'}); // create it
159159
}
160160
};
161161
```
@@ -345,7 +345,7 @@ request.onerror = function(event) {
345345
if (request.error.name == "ConstraintError") {
346346
console.log("Книга с таким id уже существует"); // обрабатываем ошибку
347347
event.preventDefault(); // предотвращаем отмену транзакции
348-
...можно попробовать использовать другой ключ...
348+
// ...можно попробовать использовать другой ключ...
349349
} else {
350350
// неизвестная ошибка
351351
// транзакция будет отменена
@@ -523,7 +523,7 @@ let request = priceIndex.getAll(IDBKeyRange.upperBound(5));
523523

524524
## Удаление из хранилища
525525

526-
Метод `delete` удаляет значения по запросу, формат вызова такой же как в `getAll`.
526+
Метод `delete` удаляет значения по запросу, формат вызова такой же как в `getAll`:
527527

528528
- **`delete(query)`** -- производит удаление соответствующих запросу значений.
529529

@@ -671,7 +671,7 @@ try {
671671

672672
### Обработка ошибок
673673

674-
Если мы не перехватим ошибку, то она "провалится" дальше, до ближайшего внешнего `try..catch`.
674+
Если мы не перехватим ошибку, то она "вывалится" наружу, вверх по стеку вызовов, до ближайшего внешнего `try..catch`.
675675

676676
Необработанная ошибка становится событием "unhandled promise rejection" в объекте `window`.
677677

9-regular-expressions/14-regexp-lookahead-lookbehind/article.md

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -60,9 +60,9 @@ alert( str.match(/(?<!\$)\d+/) ); // 2 (skipped the price)
6060

6161
Generally, what's inside the lookaround (a common name for both lookahead and lookbehind) parentheses does not become a part of the match.
6262

63-
E.g. in the pattern `pattern:\d+(?!€)`, the `pattern:€` sign doesn't get captured as a part of the match.
63+
E.g. in the pattern `pattern:\d+(?=€)`, the `pattern:€` sign doesn't get captured as a part of the match. That's natural: we look for a number `pattern:\d+`, while `pattern:(?=€)` is just a test that it should be followed by `subject:€`.
6464

65-
But if we want to capture the whole lookaround expression or a part of it, that's possible. Just need to wrap that into additional parentheses.
65+
But in some situations we might want to capture the lookaround expression as well, or a part of it. That's possible. Just wrap that into additional parentheses.
6666

6767
For instance, here the currency `pattern:(€|kr)` is captured, along with the amount:
6868

@@ -89,9 +89,13 @@ Usually parentheses are numbered left-to-right, but lookbehind is an exception,
8989

9090
## Summary
9191

92-
Lookahead and lookbehind (commonly referred to as "lookaround") are useful for simple regular expressions, when we'd like not to take something into the match depending on the context before/after it.
92+
Lookahead and lookbehind (commonly referred to as "lookaround") are useful when we'd like to take something into the match depending on the context before/after it.
9393

94-
Sometimes we can do the same manually, that is: match all and filter by context in the loop. Remember, `str.matchAll` and `reg.exec` return matches with `.index` property, so we know where exactly in the text it is. But generally regular expressions can do it better.
94+
For simple regexps we can do the similar thing manually. That is: match everything, in any context, and then filter by context in the loop.
95+
96+
Remember, `str.matchAll` and `reg.exec` return matches with `.index` property, so we know where exactly in the text it is, and can check the context.
97+
98+
But generally regular expressions are more convenient.
9599

96100
Lookaround types:
97101

@@ -102,4 +106,4 @@ Lookaround types:
102106
| `pattern:(?<=y)x` | Positive lookbehind | `x` if after `y` |
103107
| `pattern:(?<!y)x` | Negative lookbehind | `x` if not after `y` |
104108

105-
Lookahead can also used to disable backtracking. Why that may be needed -- see in the next chapter.
109+
Lookahead can also used to disable backtracking. Why that may be needed and other details -- see in the next chapter.

0 commit comments

Comments
 (0)