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/04-object-basics/02-garbage-collection/article.md
+1-1Lines changed: 1 addition & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -207,6 +207,6 @@ A general book "The Garbage Collection Handbook: The Art of Automatic Memory Man
207
207
208
208
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).
209
209
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.
211
211
212
212
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.
Copy file name to clipboardExpand all lines: 1-js/04-object-basics/04-object-methods/article.md
+13-9Lines changed: 13 additions & 9 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -63,7 +63,7 @@ user.sayHi(); // Hello!
63
63
```smart header="Object-oriented programming"
64
64
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".
65
65
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.
67
67
```
68
68
### Method shorthand
69
69
@@ -72,14 +72,14 @@ There exists a shorter syntax for methods in an object literal:
72
72
```js
73
73
// these objects do the same
74
74
75
-
letuser = {
75
+
user = {
76
76
sayHi:function() {
77
77
alert("Hello");
78
78
}
79
79
};
80
80
81
81
// method shorthand looks better, right?
82
-
letuser = {
82
+
user = {
83
83
*!*
84
84
sayHi() { // same as "sayHi: function()"
85
85
*/!*
@@ -166,7 +166,7 @@ If we used `this.name` instead of `user.name` inside the `alert`, then the code
166
166
167
167
## "this" is not bound
168
168
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.
170
170
171
171
There's no syntax error in the code like that:
172
172
@@ -176,9 +176,9 @@ function sayHi() {
176
176
}
177
177
```
178
178
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.
180
180
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:
admin['f'](); // Admin (dot or square brackets access the method – doesn't matter)
203
203
```
204
204
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:
206
209
207
210
```js run
208
211
functionsayHi() {
@@ -216,7 +219,8 @@ In this case `this` is `undefined` in strict mode. If we try to access `this.nam
216
219
217
220
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.
218
221
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
+
````
220
224
221
225
```smart header="The consequences of unbound `this`"
222
226
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.
Copy file name to clipboardExpand all lines: 1-js/05-data-types/11-json/article.md
-1Lines changed: 0 additions & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -68,7 +68,6 @@ alert(json);
68
68
69
69
Полученная строка `json` называется *JSON-форматированным* или *сериализованным* объектом. Мы можем отправить его по сети или поместить в обычное хранилище данных.
70
70
71
-
72
71
Обратите внимание, что объект в формате JSON имеет несколько важных отличий от объектного литерала:
73
72
74
73
- Строки используют двойные кавычки. Никаких одинарных кавычек или обратных кавычек в JSON. Так `'John'` становится `"John"`.
Copy file name to clipboardExpand all lines: 1-js/11-async/07-microtask-queue/article.md
+11-9Lines changed: 11 additions & 9 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -3,9 +3,9 @@
3
3
4
4
Promise handlers `.then`/`.catch`/`.finally` are always asynchronous.
5
5
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 .
7
7
8
-
Here's the code that demonstrates it:
8
+
Here's the demo:
9
9
10
10
```js run
11
11
let promise =Promise.resolve();
@@ -21,7 +21,7 @@ That's strange, because the promise is definitely done from the beginning.
21
21
22
22
Why did the `.then` trigger afterwards? What's going on?
23
23
24
-
# Microtasks
24
+
##Microtasks
25
25
26
26
Asynchronous tasks need proper management. For that, the standard specifies an internal queue `PromiseJobs`, more often referred to as "microtask queue" (v8 term).
27
27
@@ -54,9 +54,11 @@ Now the order is as intended.
54
54
55
55
## Event loop
56
56
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*.
58
58
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.
60
62
61
63
Examples of events:
62
64
-`mousemove`, a user moved their mouse.
@@ -120,14 +122,14 @@ Promise.resolve()
120
122
121
123
Naturally, `promise` shows up first, because `setTimeout` macrotask awaits in the less-priority macrotask queue.
122
124
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.
124
126
125
127
126
128
## Unhandled rejection
127
129
128
130
Remember "unhandled rejection" event from the chapter <info:promise-error-handling>?
129
131
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.
131
133
132
134
**"Unhandled rejection" is when a promise error is not handled at the end of the microtask queue.**
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.
171
173
172
174
In the example, the `.catch` added by `setTimeout` triggers too, of course it does, but later, after `unhandledrejection` has already occurred.
173
175
174
176
## Summary
175
177
176
178
- Promise handling is always asynchronous, as all promise actions pass through the internal "promise jobs" queue, also called "microtask queue" (v8 term).
177
179
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.**
179
181
180
182
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.
Copy file name to clipboardExpand all lines: 2-ui/1-document/05-basic-dom-node-properties/2-tree-info/solution.md
+2-2Lines changed: 2 additions & 2 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -6,7 +6,7 @@ for (let li of document.querySelectorAll('li')) {
6
6
}
7
7
```
8
8
9
-
В цикле нам нужно получить текст в каждом элементе `li`. Мы можем прочитать текст из первого дочернего узла `li`, который будет текстовым узлом:
9
+
В цикле нам нужно получить текст в каждом элементе `li`. Мы можем прочитать текстовое содержимое элемента списска из первого дочернего узла `li`, который будет текстовым узлом:
10
10
11
11
```js
12
12
for (let li ofdocument.querySelectorAll('li')) {
@@ -16,4 +16,4 @@ for (let li of document.querySelectorAll('li')) {
16
16
}
17
17
```
18
18
19
-
Так мы сможем получить количество потомков как `li.getElementsByTagName('li')`.length
19
+
Так мы сможем получить количество потомков как `li.getElementsByTagName('li').length`.
У других типов узлов есть свои аналоги: свойства `nodeValue` и `data`. Эти свойства очень похожи при использовании, есть лишь небольшие различия в спецификации. Мы будем использовать `data`, потому что оно короче.
328
328
329
-
Прочитаем содержимое текстового узла:
329
+
Прочитаем содержимое текстового узла и комментария:
: Мы можем получить свойство `nodeType` из класса DOM-объекта, но часто нам нужно только посмотреть, является ли элемент текстом или узлом-элементом. Свойство `nodeType` хорошо для этого подходит. В нём содержится цифровое значение, наиболее важными являются: `1` для элементов,`3` для текстовых узлов, и т.д. Только для чтения.
472
+
: Свойство `nodeType` позволяет узнать тип DOM-узла. Его значение - числовое: `1` для элементов,`3` для текстовых узлов, и т.д. Только для чтения.
473
473
474
474
`nodeName/tagName`
475
475
: Для элементов это свойство возвращает название тега (записывается в верхнем регистре, за исключением XML-режима). Для узлов-неэлементов `nodeName` описывает, что это за узел. Только для чтения.
Copy file name to clipboardExpand all lines: 2-ui/2-events/02-bubbling-and-capturing/article.md
+1-3Lines changed: 1 addition & 3 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -151,9 +151,7 @@ There are two possible values of the `capture` option:
151
151
152
152
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.
153
153
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.
Copy file name to clipboardExpand all lines: 2-ui/3-event-details/4-mouse-drag-and-drop/article.md
+2-2Lines changed: 2 additions & 2 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -4,9 +4,9 @@ Drag'n'Drop is a great interface solution. Taking something, dragging and droppi
4
4
5
5
In the modern HTML standard there's a [section about Drag Events](https://html.spec.whatwg.org/multipage/interaction.html#dnd).
6
6
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.
8
8
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.
10
10
11
11
So here we'll see how to implement Drag'n'Drop using mouse events. Not that hard either.
0 commit comments