Skip to content

Commit 029d766

Browse files
committed
merge
2 parents ba3024b + e50185a commit 029d766

File tree

23 files changed

+406
-351
lines changed

23 files changed

+406
-351
lines changed

1-js/02-first-steps/14-function-basics/article.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -340,9 +340,15 @@ return*!*;*/!*
340340
(some + long + expression + or + whatever * f(a) + f(b))
341341
```
342342
343+
<<<<<<< HEAD
343344
Таким образом, это фактически стало пустым `return`.
344345
345346
Если мы хотим, чтобы возвращаемое выражение занимало несколько строк, нужно начать его на той же строке, что и `return`. Или, хотя бы, поставить там открывающую скобку, вот так:
347+
=======
348+
So, it effectively becomes an empty return.
349+
350+
If we want the returned expression to wrap across multiple lines, we should start it at the same line as `return`. Or at least put the opening parentheses there as follows:
351+
>>>>>>> e50185af4b4df7dbe1870215e382a206241c8515
346352
347353
```js
348354
return (
@@ -351,7 +357,11 @@ return (
351357
whatever * f(a) + f(b)
352358
)
353359
```
360+
<<<<<<< HEAD
354361
И тогда всё сработает как задумано.
362+
=======
363+
And it will work just as we expect it to.
364+
>>>>>>> e50185af4b4df7dbe1870215e382a206241c8515
355365
````
356366
357367
## Выбор имени функции [#function-naming]

1-js/02-first-steps/15-function-expressions-arrows/article.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,11 @@ ask("Вы согласны?", showOk, showCancel);
132132

133133
Перед тем, как мы рассмотрим, как можно записать это гораздо короче, давайте обратим внимание, что в браузере (и в отдельных случаях на стороне сервера) подобное использование функций очень распространено. Основным отличием между реализацией таких функций в реальном проекте и примером выше является то, что в реальности функции используют более сложные способы взаимодействия с пользователем, чем простой вызов `confirm`. В браузерах такие функции обычно отображают красивые диалоговые окна. Но это уже другая история.
134134

135+
<<<<<<< HEAD
135136
**Аргументы функции `ask` ещё называют *функциями-колбэками* или просто *колбэками*.**
137+
=======
138+
**The arguments `showOk` and `showCancel` of `ask` are called *callback functions* or just *callbacks*.**
139+
>>>>>>> e50185af4b4df7dbe1870215e382a206241c8515
136140
137141
Ключевая идея в том, что мы передаём функцию и ожидаем, что она вызовется обратно (от англ. "call back" - обратный вызов) когда-нибудь позже, если это будет необходимо. В нашем случае, `showOk` становится *колбэком*' для ответа "yes", а `showCancel` -- для ответа "no".
138142

1-js/06-advanced-functions/10-bind/6-ask-partial/solution.md

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

22

3-
1. Либо для краткости используйте стрелочную функцию-обёртку:
3+
1. Either use a wrapper function, an arrow to be concise:
44

55
```js
66
askPassword(() => user.login(true), () => user.login(false));
77
```
88

9-
Теперь `user` берётся из внешних переменных, и всё выполняется правильно.
9+
Now it gets `user` from outer variables and runs it the normal way.
1010

11-
2. Либо сделайте из `user.login` функцию частичного применения, которая использует `user` как контекст, и которой передан корректный первый аргумент:
11+
2. Or create a partial function from `user.login` that uses `user` as the context and has the correct first argument:
1212

1313

1414
```js

1-js/06-advanced-functions/10-bind/6-ask-partial/task.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@ importance: 5
22

33
---
44

5-
# Частичное применение для логина
5+
# Partial application for login
66

7-
Эта задача -- немного более усложнённый вариант <info:task/question-use-bind>.
7+
The task is a little more complex variant of <info:task/question-use-bind>.
88

9-
Объект `user` был изменён. Теперь вместо двух функций `loginOk/loginFail`, у него одна функция: `user.login(true/false)`.
9+
The `user` object was modified. Now instead of two functions `loginOk/loginFail`, it has a single function `user.login(true/false)`.
1010

11-
Что нужно передать функции `askPassword` в коде ниже, чтобы она вызывала `user.login(true)` как `ok` и `user.login(false)` как `fail`?
11+
What to pass `askPassword` in the code below, so that it calls `user.login(true)` as `ok` and `user.login(false)` as `fail`?
1212

1313
```js
1414
function askPassword(ok, fail) {
@@ -30,5 +30,5 @@ askPassword(?, ?); // ?
3030
*/!*
3131
```
3232
33-
Вы можете изменять только подсвеченные фрагменты кода.
33+
Your changes should only modify the highlighted fragment.
3434

1-js/06-advanced-functions/10-bind/article.md

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,28 +194,49 @@ for (let key in user) {
194194
Некоторые JS-библиотеки предоставляют встроенные функции для удобной массовой привязки контекста, например [_.bindAll(obj)](http://lodash.com/docs#bindAll) в lodash.
195195
````
196196
197+
<<<<<<< HEAD
197198
## Частичное применение
198199
199200
До сих пор мы говорили только о привязывании `this`. Давайте шагнём дальше.
200201
201202
Мы можем привязать не только `this`, но и аргументы. Это делается редко, но иногда может быть полезно.
202203
203204
Полный синтаксис `bind`:
205+
=======
206+
## Partial functions
207+
208+
Until now we have only been talking about binding `this`. Let's take it a step further.
209+
210+
We can bind not only `this`, but also arguments. That's rarely done, but sometimes can be handy.
211+
212+
The full syntax of `bind`:
213+
>>>>>>> e50185af4b4df7dbe1870215e382a206241c8515
204214
205215
```js
206216
let bound = func.bind(context, [arg1], [arg2], ...);
207217
```
218+
<<<<<<< HEAD
208219
Это позволяет привязать контекст `this` и начальные аргументы функции.
209220
210221
Например, у нас есть функция умножения `mul(a, b)`:
222+
=======
223+
224+
It allows to bind context as `this` and starting arguments of the function.
225+
226+
For instance, we have a multiplication function `mul(a, b)`:
227+
>>>>>>> e50185af4b4df7dbe1870215e382a206241c8515
211228
212229
```js
213230
function mul(a, b) {
214231
return a * b;
215232
}
216233
```
217234
235+
<<<<<<< HEAD
218236
Давайте воспользуемся `bind`, чтобы создать функцию `double` на её основе:
237+
=======
238+
Let's use `bind` to create a function `double` on its base:
239+
>>>>>>> e50185af4b4df7dbe1870215e382a206241c8515
219240
220241
```js run
221242
function mul(a, b) {
@@ -231,13 +252,23 @@ alert( double(4) ); // = mul(2, 4) = 8
231252
alert( double(5) ); // = mul(2, 5) = 10
232253
```
233254
255+
<<<<<<< HEAD
234256
Вызов `mul.bind(null, 2)` создаёт новую функцию `double`, которая передаёт вызов `mul`, фиксируя `null` как контекст и `2` -- как первый аргумент. Следующие аргументы передаются "как есть".
235257
236258
Это называется [частичное применение](https://ru.wikipedia.org/wiki/Частичное_применение) -- мы создаём новую функцию, фиксируя некоторые из существующих параметров.
237259
238260
Обратите внимание, что в данном случае мы на самом деле не используем `this`. Но для `bind` это обязательный параметр, так что мы должны передать туда что-нибудь вроде `null`.
239261
240262
В следующем коде функция `triple` умножает значение на три:
263+
=======
264+
The call to `mul.bind(null, 2)` creates a new function `double` that passes calls to `mul`, fixing `null` as the context and `2` as the first argument. Further arguments are passed "as is".
265+
266+
That's called [partial function application](https://en.wikipedia.org/wiki/Partial_application) -- we create a new function by fixing some parameters of the existing one.
267+
268+
Please note that here we actually don't use `this` here. But `bind` requires it, so we must put in something like `null`.
269+
270+
The function `triple` in the code below triples the value:
271+
>>>>>>> e50185af4b4df7dbe1870215e382a206241c8515
241272
242273
```js run
243274
function mul(a, b) {
@@ -253,6 +284,7 @@ alert( triple(4) ); // = mul(3, 4) = 12
253284
alert( triple(5) ); // = mul(3, 5) = 15
254285
```
255286
287+
<<<<<<< HEAD
256288
Для чего мы обычно создаём частично применённую функцию?
257289
258290
Польза от этого в том, что возможно создать независимую функцию с понятным названием (`double`, `triple`). Мы можем использовать её и не передавать каждый раз первый аргумент, т.к. он зафиксирован с помощью `bind`.
@@ -270,6 +302,25 @@ alert( triple(5) ); // = mul(3, 5) = 15
270302
К счастью, лекго создать вспомогательную функцию `partial`, которая привязывает только аргументы.
271303
272304
Вот так:
305+
=======
306+
Why do we usually make a partial function?
307+
308+
The benefit is that we can create an independent function with a readable name (`double`, `triple`). We can use it and not provide first argument of every time as it's fixed with `bind`.
309+
310+
In other cases, partial application is useful when we have a very generic function and want a less universal variant of it for convenience.
311+
312+
For instance, we have a function `send(from, to, text)`. Then, inside a `user` object we may want to use a partial variant of it: `sendTo(to, text)` that sends from the current user.
313+
314+
## Going partial without context
315+
316+
What if we'd like to fix some arguments, but not the context `this`? For example, for an object method.
317+
318+
The native `bind` does not allow that. We can't just omit the context and jump to arguments.
319+
320+
Fortunately, a helper function `partial` for binding only arguments can be easily implemented.
321+
322+
Like this:
323+
>>>>>>> e50185af4b4df7dbe1870215e382a206241c8515
273324
274325
```js run
275326
*!*
@@ -280,14 +331,19 @@ function partial(func, ...argsBound) {
280331
}
281332
*/!*
282333
334+
<<<<<<< HEAD
283335
// использование:
336+
=======
337+
// Usage:
338+
>>>>>>> e50185af4b4df7dbe1870215e382a206241c8515
284339
let user = {
285340
firstName: "John",
286341
say(time, phrase) {
287342
alert(`[${time}] ${this.firstName}: ${phrase}!`);
288343
}
289344
};
290345
346+
<<<<<<< HEAD
291347
// добавляем частично применённый метод с фиксированным временем
292348
user.sayNow = partial(user.say, new Date().getHours() + ':' + new Date().getMinutes());
293349
@@ -310,7 +366,35 @@ user.sayNow("Hello");
310366
Метод `bind` возвращает "привязанный вариант" функции `func`, фиксируя контекст `this` и первые аргументы `arg1`, `arg2`..., если они заданы.
311367
312368
Обычно `bind` применяется для фиксации `this` в методе объекта, чтобы передать его в качестве колбэка. Например, для `setTimeout`.
369+
=======
370+
// add a partial method with fixed time
371+
user.sayNow = partial(user.say, new Date().getHours() + ':' + new Date().getMinutes());
372+
373+
user.sayNow("Hello");
374+
// Something like:
375+
// [10:00] John: Hello!
376+
```
377+
378+
The result of `partial(func[, arg1, arg2...])` call is a wrapper `(*)` that calls `func` with:
379+
- Same `this` as it gets (for `user.sayNow` call it's `user`)
380+
- Then gives it `...argsBound` -- arguments from the `partial` call (`"10:00"`)
381+
- Then gives it `...args` -- arguments given to the wrapper (`"Hello"`)
382+
383+
So easy to do it with the spread operator, right?
384+
385+
Also there's a ready [_.partial](https://lodash.com/docs#partial) implementation from lodash library.
386+
387+
## Summary
388+
>>>>>>> e50185af4b4df7dbe1870215e382a206241c8515
313389
314390
Когда мы привязываем аргументы, такая функция называется "частично применённой" или "частичной".
315391
392+
<<<<<<< HEAD
316393
Частичное применение удобно, когда мы не хотим повторять один и тот же аргумент много раз. Например, когда у нас есть функция `send(from, to)`, и `from` всё время будет одинаков для нашей задачи, мы можем создать частично применённую функцию и дальше работать с ней.
394+
=======
395+
Usually we apply `bind` to fix `this` for an object method, so that we can pass it somewhere. For example, to `setTimeout`.
396+
397+
When we fix some arguments of an existing function, the resulting (less universal) function is called *partially applied* or *partial*.
398+
399+
Partials are convenient when we don't want to repeat the same argument over and over again. Like if we have a `send(from, to)` function, and `from` should always be the same for our task, we can get a partial and go on with it.
400+
>>>>>>> e50185af4b4df7dbe1870215e382a206241c8515

1-js/07-object-properties/01-property-descriptors/article.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,11 @@ Object.defineProperty(obj, propertyName, descriptor)
6363
```
6464

6565
`obj`, `propertyName`
66+
<<<<<<< HEAD
6667
: Объект и его свойство, для которого нужно применить дескриптор.
68+
=======
69+
: The object and its property to apply the descriptor.
70+
>>>>>>> e50185af4b4df7dbe1870215e382a206241c8515
6771
6872
`descriptor`
6973
: Применяемый дескриптор.
@@ -116,7 +120,11 @@ Object.defineProperty(user, "name", {
116120
});
117121

118122
*!*
123+
<<<<<<< HEAD
119124
user.name = "Pete"; // Ошибка: Невозможно изменить доступное только для чтения свойство 'name'
125+
=======
126+
user.name = "Pete"; // Error: Cannot assign to read only property 'name'
127+
>>>>>>> e50185af4b4df7dbe1870215e382a206241c8515
120128
*/!*
121129
```
122130

@@ -126,27 +134,44 @@ user.name = "Pete"; // Ошибка: Невозможно изменить до
126134
В нестрогом режиме, без `use strict`, мы не увидим никаких ошибок при записи в свойства "только для чтения" и т.п. Но эти операции всё равно не будут выполнены успешно. Действия, нарушающие ограничения флагов, в нестрогом режиме просто молча игнорируются.
127135
```
128136

137+
<<<<<<< HEAD
129138
Вот тот же пример, но свойство создано "с нуля":
139+
=======
140+
Here's the same example, but the property is created from scratch:
141+
>>>>>>> e50185af4b4df7dbe1870215e382a206241c8515
130142
131143
```js run
132144
let user = { };
133145

134146
Object.defineProperty(user, "name", {
135147
*!*
136148
value: "John",
149+
<<<<<<< HEAD
137150
// для нового свойства необходимо явно указывать все флаги, для которых значение true
151+
=======
152+
// for new properties need to explicitly list what's true
153+
>>>>>>> e50185af4b4df7dbe1870215e382a206241c8515
138154
enumerable: true,
139155
configurable: true
140156
*/!*
141157
});
142158

143159
alert(user.name); // John
160+
<<<<<<< HEAD
144161
user.name = "Pete"; // Ошибка
145162
```
146163

147164
## Неперечислимое свойство
148165

149166
Теперь добавим собственный метод `toString` к объекту `user`.
167+
=======
168+
user.name = "Pete"; // Error
169+
```
170+
171+
## Non-enumerable
172+
173+
Now let's add a custom `toString` to `user`.
174+
>>>>>>> e50185af4b4df7dbe1870215e382a206241c8515
150175
151176
Встроенный метод `toString` в объектах - неперечислимый, его не видно в цикле `for..in`. Но если мы напишем свой собственный метод `toString`, цикл `for..in` будет выводить его по умолчанию:
152177

1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit-walk-2.svg

Lines changed: 1 addition & 1 deletion
Loading

1-js/08-prototypes/01-prototype-inheritance/proto-animal-rabbit-walk.svg

Lines changed: 1 addition & 1 deletion
Loading

0 commit comments

Comments
 (0)