Skip to content

Commit 6454952

Browse files
authored
Function binding (#203)
1 parent 4f67dc2 commit 6454952

File tree

11 files changed

+149
-149
lines changed

11 files changed

+149
-149
lines changed

1-js/06-advanced-functions/10-bind/2-write-to-object-after-bind/solution.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
The answer: `null`.
1+
Відповідь: `null`.
22

33

44
```js run
@@ -13,6 +13,6 @@ let user = {
1313
user.g();
1414
```
1515

16-
The context of a bound function is hard-fixed. There's just no way to further change it.
16+
Контекст прив’язаної функції жорстко-фіксований. Немає способу змінити це в подальшому.
1717

18-
So even while we run `user.g()`, the original function is called with `this=null`.
18+
Так чином в той час як ми запускаємо `user.g()`, функція `f` викликається з `this=null`.

1-js/06-advanced-functions/10-bind/2-write-to-object-after-bind/task.md

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

33
---
44

5-
# Bound function as a method
5+
# Прив’язана функція як метод
66

7-
What will be the output?
7+
Що виведе функція?
88

99
```js
1010
function f() {
Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
1-
The answer: **John**.
1+
Відповідь: **Іван**.
22

33
```js run no-beautify
44
function f() {
55
alert(this.name);
66
}
77

8-
f = f.bind( {name: "John"} ).bind( {name: "Pete"} );
8+
f = f.bind( {name: "Іван"} ).bind( {name: "Христя"} );
99

10-
f(); // John
10+
f(); // Іван
1111
```
1212

13-
The exotic [bound function](https://tc39.github.io/ecma262/#sec-bound-function-exotic-objects) object returned by `f.bind(...)` remembers the context (and arguments if provided) only at creation time.
13+
Екзотичний об’єкт [прив’язаної функції](https://tc39.github.io/ecma262/#sec-bound-function-exotic-objects) повертається від `f.bind(...)`, що запам’ятовує контекст (та аргументи, якщо передані) тільки під час створення.
1414

15-
A function cannot be re-bound.
15+
Функція не може бути переприв’язана.

1-js/06-advanced-functions/10-bind/3-second-bind/task.md

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

33
---
44

5-
# Second bind
5+
# Друга прив’язка
66

7-
Can we change `this` by additional binding?
7+
Чи можемо ми змінити `this` за допомогою додаткового прив’язування?
88

9-
What will be the output?
9+
Який результат буде виведено?
1010

1111
```js no-beautify
1212
function f() {
1313
alert(this.name);
1414
}
1515

16-
f = f.bind( {name: "John"} ).bind( {name: "Ann" } );
16+
f = f.bind( {name: "Іван"} ).bind( {name: "Христя" } );
1717

1818
f();
1919
```
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
The answer: `undefined`.
1+
Відповідь: `undefined`.
22

3-
The result of `bind` is another object. It does not have the `test` property.
3+
Результатом `bind` є інший об’єкт. Він не містить властивість `test`.
44

1-js/06-advanced-functions/10-bind/4-function-property-after-bind/task.md

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

33
---
44

5-
# Function property after bind
5+
# Властивість функції після прив’язки
66

7-
There's a value in the property of a function. Will it change after `bind`? Why, or why not?
7+
Функції присвоєна властивість зі значенням. Чи зміниться вона після `bind`? Чому?
88

99
```js run
1010
function sayHi() {
@@ -14,10 +14,10 @@ sayHi.test = 5;
1414

1515
*!*
1616
let bound = sayHi.bind({
17-
name: "John"
17+
name: "Іван"
1818
});
1919

20-
alert( bound.test ); // what will be the output? why?
20+
alert( bound.test ); // що виведе функція? Чому?
2121
*/!*
2222
```
2323

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

2-
The error occurs because `ask` gets functions `loginOk/loginFail` without the object.
2+
Помилка виникає тому що `askPassword` отримує функції `loginOk/loginFail` без об’єкту.
33

4-
When it calls them, they naturally assume `this=undefined`.
4+
Коли вона викликає їх, їх контекст втрачено `this=undefined`.
55

6-
Let's `bind` the context:
6+
Спробуємо використати `bind`, щоб прив’язати контекст:
77

88
```js run
99
function askPassword(ok, fail) {
10-
let password = prompt("Password?", '');
10+
let password = prompt("Пароль?", '');
1111
if (password == "rockstar") ok();
1212
else fail();
1313
}
1414

1515
let user = {
16-
name: 'John',
16+
name: 'Іван',
1717

1818
loginOk() {
19-
alert(`${this.name} logged in`);
19+
alert(`${this.name} увійшов`);
2020
},
2121

2222
loginFail() {
23-
alert(`${this.name} failed to log in`);
23+
alert(`${this.name} виконав невдалу спробу входу`);
2424
},
2525

2626
};
@@ -30,14 +30,14 @@ askPassword(user.loginOk.bind(user), user.loginFail.bind(user));
3030
*/!*
3131
```
3232

33-
Now it works.
33+
Тепер це працює.
3434

35-
An alternative solution could be:
35+
Альтернативне рішення могло б бути:
3636
```js
3737
//...
3838
askPassword(() => user.loginOk(), () => user.loginFail());
3939
```
4040

41-
Usually that also works and looks good.
41+
Зазвичай це також працює та чудово виглядає.
4242

43-
It's a bit less reliable though in more complex situations where `user` variable might change *after* `askPassword` is called, but *before* the visitor answers and calls `() => user.loginOk()`.
43+
Це менш найдіно, так як в більш складних ситуаціях змінна `user` може змінитися *після* виклику `askPassword`, але *перед* викликом `() => user.loginOk()`.

1-js/06-advanced-functions/10-bind/5-question-use-bind/task.md

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

33
---
44

5-
# Fix a function that loses "this"
5+
# Виправте функцію, яка втратила 'this'
66

7-
The call to `askPassword()` in the code below should check the password and then call `user.loginOk/loginFail` depending on the answer.
7+
Виклик `askPassword()` в коді наведеному нижче повинен перевіряти пароль та викликати `user.loginOk/loginFail` в залежності від відповіді.
88

9-
But it leads to an error. Why?
9+
Але виконання коду призводить до помилки. Чому?
1010

11-
Fix the highlighted line for everything to start working right (other lines are not to be changed).
11+
Виправте виділений рядок, щоб код запрацював правильно (інші рядки не мають бути змінені).
1212

1313
```js run
1414
function askPassword(ok, fail) {
15-
let password = prompt("Password?", '');
15+
let password = prompt("Пароль?", '');
1616
if (password == "rockstar") ok();
1717
else fail();
1818
}
1919

2020
let user = {
21-
name: 'John',
21+
name: 'Іван',
2222

2323
loginOk() {
24-
alert(`${this.name} logged in`);
24+
alert(`${this.name} увійшов`);
2525
},
2626

2727
loginFail() {
28-
alert(`${this.name} failed to log in`);
28+
alert(`${this.name} виконав невдалу спробу входу`);
2929
},
3030

3131
};

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. Either use a wrapper function, an arrow to be concise:
3+
1. Або використовуйте стрілкову функцію як функцію-обгортку для короткого запису:
44

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

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

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

1313

1414
```js

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

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

33
---
44

5-
# Partial application for login
5+
# Часткове застосування для логіну
66

7-
The task is a little more complex variant of <info:task/question-use-bind>.
7+
Задача трохи складніша ніж <info:task/question-use-bind>.
88

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

11-
What should we pass `askPassword` in the code below, so that it calls `user.login(true)` as `ok` and `user.login(false)` as `fail`?
11+
Що ми маємо передати `askPassword` в коді нижче, щоб вона викликала `user.login(true)` при `ok` та `user.login(false)` при `fail`?
1212

1313
```js
1414
function askPassword(ok, fail) {
15-
let password = prompt("Password?", '');
15+
let password = prompt("Пароль?", '');
1616
if (password == "rockstar") ok();
1717
else fail();
1818
}
1919

2020
let user = {
21-
name: 'John',
21+
name: 'Іван',
2222

2323
login(result) {
24-
alert( this.name + (result ? ' logged in' : ' failed to log in') );
24+
alert( this.name + (result ? ' увійшов' : ' виконав невдалу спробу входу') );
2525
}
2626
};
2727

@@ -30,5 +30,5 @@ askPassword(?, ?); // ?
3030
*/!*
3131
```
3232
33-
Your changes should only modify the highlighted fragment.
33+
Вносіть зміни тільки у виділений рядок.
3434

0 commit comments

Comments
 (0)