Skip to content

Commit 3e2002b

Browse files
committed
2 parents c881d1a + 0e97922 commit 3e2002b

12 files changed

Lines changed: 40 additions & 37 deletions

File tree

1-js/04-object-basics/02-garbage-collection/article.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,6 @@ A general book "The Garbage Collection Handbook: The Art of Automatic Memory Man
207207

208208
If you are familiar with low-level programming, the more detailed information about V8 garbage collector is in the article [A tour of V8: Garbage Collection](http://jayconrod.com/posts/55/a-tour-of-v8-garbage-collection).
209209

210-
[V8 blog](http://v8project.blogspot.com/) also publishes articles about changes in memory management from time to time. Naturally, to learn the garbage collection, you'd better prepare by learning about V8 internals in general and read the blog of [Vyacheslav Egorov](http://mrale.ph) who worked as one of V8 engineers. I'm saying: "V8", because it is best covered with articles in the internet. For other engines, many approaches are similar, but garbage collection differs in many aspects.
210+
[V8 blog](https://v8.dev/) also publishes articles about changes in memory management from time to time. Naturally, to learn the garbage collection, you'd better prepare by learning about V8 internals in general and read the blog of [Vyacheslav Egorov](http://mrale.ph) who worked as one of V8 engineers. I'm saying: "V8", because it is best covered with articles in the internet. For other engines, many approaches are similar, but garbage collection differs in many aspects.
211211

212212
In-depth knowledge of engines is good when you need low-level optimizations. It would be wise to plan that as the next step after you're familiar with the language.

1-js/04-object-basics/04-object-methods/article.md

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ user.sayHi(); // Hello!
6363
```smart header="Object-oriented programming"
6464
When we write our code using objects to represent entities, that's called an [object-oriented programming](https://en.wikipedia.org/wiki/Object-oriented_programming), in short: "OOP".
6565
66-
OOP is a big thing, an interesting science of its own. How to choose the right entities? How to organize the interaction between them? That's architecture, and there are great books on that topic, like "Design Patterns: Elements of Reusable Object-Oriented Software" by E.Gamma, R.Helm, R.Johnson, J.Vissides or "Object-Oriented Analysis and Design with Applications" by G.Booch, and more.
66+
OOP is a big thing, an interesting science of its own. How to choose the right entities? How to organize the interaction between them? That's architecture, and there are great books on that topic, like "Design Patterns: Elements of Reusable Object-Oriented Software" by E.Gamma, R.Helm, R.Johnson, J.Vissides or "Object-Oriented Analysis and Design with Applications" by G.Booch, and more.
6767
```
6868
### Method shorthand
6969

@@ -72,14 +72,14 @@ There exists a shorter syntax for methods in an object literal:
7272
```js
7373
// these objects do the same
7474

75-
let user = {
75+
user = {
7676
sayHi: function() {
7777
alert("Hello");
7878
}
7979
};
8080

8181
// method shorthand looks better, right?
82-
let user = {
82+
user = {
8383
*!*
8484
sayHi() { // same as "sayHi: function()"
8585
*/!*
@@ -166,7 +166,7 @@ If we used `this.name` instead of `user.name` inside the `alert`, then the code
166166

167167
## "this" is not bound
168168

169-
In JavaScript, "this" keyword behaves unlike most other programming languages. First, it can be used in any function.
169+
In JavaScript, "this" keyword behaves unlike most other programming languages. It can be used in any function.
170170

171171
There's no syntax error in the code like that:
172172

@@ -176,9 +176,9 @@ function sayHi() {
176176
}
177177
```
178178

179-
The value of `this` is evaluated during the run-time. And it can be anything.
179+
The value of `this` is evaluated during the run-time, depending on the context. And it can be anything.
180180

181-
For instance, the same function may have different "this" when called from different objects:
181+
For instance, here the same function is assigned to two different objects and has different "this" in the calls:
182182

183183
```js run
184184
let user = { name: "John" };
@@ -189,7 +189,7 @@ function sayHi() {
189189
}
190190

191191
*!*
192-
// use the same functions in two objects
192+
// use the same function in two objects
193193
user.f = sayHi;
194194
admin.f = sayHi;
195195
*/!*
@@ -202,7 +202,10 @@ admin.f(); // Admin (this == admin)
202202
admin['f'](); // Admin (dot or square brackets access the method – doesn't matter)
203203
```
204204

205-
Actually, we can call the function without an object at all:
205+
The rule is simple: if `obj.f()` is called, then `this` is `obj` during the call of `f`. So it's either `user` or `admin` in the example above.
206+
207+
````smart header="Calling without an object: `this == undefined`"
208+
We can even call the function without an object at all:
206209

207210
```js run
208211
function sayHi() {
@@ -216,7 +219,8 @@ In this case `this` is `undefined` in strict mode. If we try to access `this.nam
216219

217220
In non-strict mode the value of `this` in such case will be the *global object* (`window` in a browser, we'll get to it later in the chapter [](info:global-object)). This is a historical behavior that `"use strict"` fixes.
218221

219-
Please note that usually a call of a function that uses `this` without an object is not normal, but rather a programming mistake. If a function has `this`, then it is usually meant to be called in the context of an object.
222+
Usually such call is an programming error. If there's `this` inside a function, it expects to be called in an object context.
223+
````
220224
221225
```smart header="The consequences of unbound `this`"
222226
If you come from another programming language, then you are probably used to the idea of a "bound `this`", where methods defined in an object always have `this` referencing that object.

1-js/05-data-types/02-number/3-repeat-until-number/_js.view/test.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ describe("readNumber", function() {
1818
assert.strictEqual(readNumber(), 0);
1919
});
2020

21-
it("continues the loop unti meets a number", function() {
21+
it("continues the loop until meets a number", function() {
2222
prompt.onCall(0).returns("not a number");
2323
prompt.onCall(1).returns("not a number again");
2424
prompt.onCall(2).returns("1");
@@ -35,4 +35,4 @@ describe("readNumber", function() {
3535
assert.isNull(readNumber());
3636
});
3737

38-
});
38+
});

1-js/05-data-types/11-json/article.md

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,6 @@ alert(json);
6868

6969
Полученная строка `json` называется *JSON-форматированным* или *сериализованным* объектом. Мы можем отправить его по сети или поместить в обычное хранилище данных.
7070

71-
7271
Обратите внимание, что объект в формате JSON имеет несколько важных отличий от объектного литерала:
7372

7473
- Строки используют двойные кавычки. Никаких одинарных кавычек или обратных кавычек в JSON. Так `'John'` становится `"John"`.

1-js/11-async/07-microtask-queue/article.md

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@
33

44
Promise handlers `.then`/`.catch`/`.finally` are always asynchronous.
55

6-
Even when a Promise is immediately resolved, the code on the lines *below* your `.then`/`.catch`/`.finally` will still execute first.
6+
Even when a Promise is immediately resolved, the code on the lines *below* `.then`/`.catch`/`.finally` will still execute before these handlers .
77

8-
Here's the code that demonstrates it:
8+
Here's the demo:
99

1010
```js run
1111
let promise = Promise.resolve();
@@ -21,7 +21,7 @@ That's strange, because the promise is definitely done from the beginning.
2121

2222
Why did the `.then` trigger afterwards? What's going on?
2323

24-
# Microtasks
24+
## Microtasks
2525

2626
Asynchronous tasks need proper management. For that, the standard specifies an internal queue `PromiseJobs`, more often referred to as "microtask queue" (v8 term).
2727

@@ -54,9 +54,11 @@ Now the order is as intended.
5454

5555
## Event loop
5656

57-
In-browser JavaScript, as well as Node.js, is based on an *event loop*.
57+
In-browser JavaScript execution flow, as well as Node.js, is based on an *event loop*.
5858

59-
"Event loop" is a process when the engine sleeps and waits for events, then reacts on those and sleeps again.
59+
"Event loop" is a process when the engine sleeps and waits for events. When they occur - handles them and sleeps again.
60+
61+
Events may come either comes from external sources, like user actions, or just as the end signal of an internal task.
6062

6163
Examples of events:
6264
- `mousemove`, a user moved their mouse.
@@ -120,14 +122,14 @@ Promise.resolve()
120122

121123
Naturally, `promise` shows up first, because `setTimeout` macrotask awaits in the less-priority macrotask queue.
122124

123-
As a logical consequence, macrotasks are handled only when promises give the engine a "free time". So if we have a promise chain that doesn't wait for anything, then things like `setTimeout` or event handlers can never get in the middle.
125+
As a logical consequence, macrotasks are handled only when promises give the engine a "free time". So if we have a chain of promise handlers that don't wait for anything, execute right one after another, then a `setTimeout` (or a user action handler) can never run in-between them.
124126

125127

126128
## Unhandled rejection
127129

128130
Remember "unhandled rejection" event from the chapter <info:promise-error-handling>?
129131

130-
Now, with the understanding of microtasks, we can formalize it.
132+
Now we can describe how JavaScript finds out that a rejection was not handled.
131133

132134
**"Unhandled rejection" is when a promise error is not handled at the end of the microtask queue.**
133135

@@ -167,15 +169,15 @@ setTimeout(() => promise.catch(err => alert('caught')));
167169
window.addEventListener('unhandledrejection', event => alert(event.reason));
168170
```
169171

170-
Now the unhandled rejection appears again. Why? Because `unhandledrejection` triggers when the microtask queue is complete. The engine examines promises and, if any of them is in "rejected" state, then the event is generated.
172+
Now the unhandled rejection appears again. Why? Because `unhandledrejection` is generated when the microtask queue is complete. The engine examines promises and, if any of them is in "rejected" state, then the event triggers.
171173

172174
In the example, the `.catch` added by `setTimeout` triggers too, of course it does, but later, after `unhandledrejection` has already occurred.
173175

174176
## Summary
175177

176178
- Promise handling is always asynchronous, as all promise actions pass through the internal "promise jobs" queue, also called "microtask queue" (v8 term).
177179

178-
**So, `.then/catch/finally` are called after the current code is finished.**
180+
**So, `.then/catch/finally` handlers are called after the current code is finished.**
179181

180182
If we need to guarantee that a piece of code is executed after `.then/catch/finally`, it's best to add it into a chained `.then` call.
181183

2-ui/1-document/05-basic-dom-node-properties/2-tree-info/solution.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ for (let li of document.querySelectorAll('li')) {
66
}
77
```
88

9-
В цикле нам нужно получить текст в каждом элементе `li`. Мы можем прочитать текст из первого дочернего узла `li`, который будет текстовым узлом:
9+
В цикле нам нужно получить текст в каждом элементе `li`. Мы можем прочитать текстовое содержимое элемента списска из первого дочернего узла `li`, который будет текстовым узлом:
1010

1111
```js
1212
for (let li of document.querySelectorAll('li')) {
@@ -16,4 +16,4 @@ for (let li of document.querySelectorAll('li')) {
1616
}
1717
```
1818

19-
Так мы сможем получить количество потомков как `li.getElementsByTagName('li')`.length
19+
Так мы сможем получить количество потомков как `li.getElementsByTagName('li').length`.

2-ui/1-document/05-basic-dom-node-properties/4-where-document-in-hierarchy/solution.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ alert(document.constructor.name); // HTMLDocument
2727
alert(HTMLDocument.prototype.constructor === HTMLDocument); // true
2828
```
2929

30-
Чтобы получить имя класса в строковой форме, используем `constructor.name`. Сделаем это для всей цепочки прототипов `document` до класса `Node`:
30+
Чтобы получить имя класса в строковой форме, используем `constructor.name`. Сделаем это для всей цепочки прототипов `document` вверх до класса `Node`:
3131

3232
```js run
3333
alert(HTMLDocument.prototype.constructor.name); // HTMLDocument

2-ui/1-document/05-basic-dom-node-properties/article.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -326,7 +326,7 @@ elem.innerHTML = elem.innerHTML + "..."
326326
327327
У других типов узлов есть свои аналоги: свойства `nodeValue` и `data`. Эти свойства очень похожи при использовании, есть лишь небольшие различия в спецификации. Мы будем использовать `data`, потому что оно короче.
328328
329-
Прочитаем содержимое текстового узла:
329+
Прочитаем содержимое текстового узла и комментария:
330330
331331
```html run height="50"
332332
<body>
@@ -469,7 +469,7 @@ elem.innerHTML = elem.innerHTML + "..."
469469
Главные свойства DOM-узла:
470470
471471
`nodeType`
472-
: Мы можем получить свойство `nodeType` из класса DOM-объекта, но часто нам нужно только посмотреть, является ли элемент текстом или узлом-элементом. Свойство `nodeType` хорошо для этого подходит. В нём содержится цифровое значение, наиболее важными являются: `1` для элементов,`3` для текстовых узлов, и т.д. Только для чтения.
472+
: Свойство `nodeType` позволяет узнать тип DOM-узла. Его значение - числовое: `1` для элементов,`3` для текстовых узлов, и т.д. Только для чтения.
473473
474474
`nodeName/tagName`
475475
: Для элементов это свойство возвращает название тега (записывается в верхнем регистре, за исключением XML-режима). Для узлов-неэлементов `nodeName` описывает, что это за узел. Только для чтения.

2-ui/2-events/02-bubbling-and-capturing/article.md

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -151,9 +151,7 @@ There are two possible values of the `capture` option:
151151

152152
Note that while formally there are 3 phases, the 2nd phase ("target phase": the event reached the element) is not handled separately: handlers on both capturing and bubbling phases trigger at that phase.
153153

154-
If one puts capturing and bubbling handlers on the target element, the capture handler triggers last in the capturing phase and the bubble handler triggers first in the bubbling phase.
155-
156-
Let's see it in action:
154+
Let's see both capturing and bubbling in action:
157155

158156
```html run autorun height=140 edit
159157
<style>

2-ui/3-event-details/4-mouse-drag-and-drop/article.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@ Drag'n'Drop is a great interface solution. Taking something, dragging and droppi
44

55
In the modern HTML standard there's a [section about Drag Events](https://html.spec.whatwg.org/multipage/interaction.html#dnd).
66

7-
They are interesting, because they allow to solve simple tasks easily, and also allow to handle drag'n'drop of "external" files into the browser. So we can take a file in the OS file-manager and drop it into the browser window. Then JavaScript gains access to its contents.
7+
They are interesting because they allow to solve simple tasks easily, and also allow to handle drag'n'drop of "external" files into the browser. So we can take a file in the OS file-manager and drop it into the browser window. Then JavaScript gains access to its contents.
88

9-
But native Drag Events also have limitations. For instance, we can limit dragging by a certain area. Also we can't make it "horizontal" or "vertical" only. There are other drag'n'drop tasks that can't be implemented using that API.
9+
But native Drag Events also have limitations. For instance, we can't limit dragging by a certain area. Also we can't make it "horizontal" or "vertical" only. There are other drag'n'drop tasks that can't be implemented using that API.
1010

1111
So here we'll see how to implement Drag'n'Drop using mouse events. Not that hard either.
1212

0 commit comments

Comments
 (0)