Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
The answer: `null`.
A resposta: `null`.


```js run
Expand All @@ -13,6 +13,6 @@ let user = {
user.g();
```

The context of a bound function is hard-fixed. There's just no way to further change it.
O contexto de uma função vinculada é fixado de forma definitiva. Não tem como mudá-lo depois.

So even while we run `user.g()`, the original function is called with `this=null`.
Então, mesmo quando rodamos `user.g()`, a função original é chamada com `this=null`.
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ importance: 5

---

# Bound function as a method
# Função vinculada como um método

What will be the output?
Qual vai ser a saída?

```js
function f() {
Expand Down
6 changes: 3 additions & 3 deletions 1-js/06-advanced-functions/10-bind/3-second-bind/solution.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
The answer: **John**.
A resposta: **John**.

```js run no-beautify
function f() {
Expand All @@ -10,6 +10,6 @@ f = f.bind( {name: "John"} ).bind( {name: "Pete"} );
f(); // John
```

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.
O objeto exótico [função vinculada](https://tc39.github.io/ecma262/#sec-bound-function-exotic-objects) retornado por `f.bind(...)` lembra o contexto (e os argumentos, se fornecidos) só no momento da criação.

A function cannot be re-bound.
Uma função não pode ser revinculada.
6 changes: 3 additions & 3 deletions 1-js/06-advanced-functions/10-bind/3-second-bind/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ importance: 5

---

# Second bind
# Segundo bind

Can we change `this` by additional binding?
Podemos mudar o `this` com um vínculo adicional?

What will be the output?
Qual vai ser a saída?

```js no-beautify
function f() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
The answer: `undefined`.
A resposta: `undefined`.

The result of `bind` is another object. It does not have the `test` property.
O resultado do `bind` é um outro objeto. Ele não tem a propriedade `test`.

Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ importance: 5

---

# Function property after bind
# Propriedade de função depois do bind

There's a value in the property of a function. Will it change after `bind`? Why, or why not?
Existe um valor na propriedade de uma função. Ele vai mudar depois do `bind`? Por que sim, ou por que não?

```js run
function sayHi() {
Expand All @@ -17,7 +17,7 @@ let bound = sayHi.bind({
name: "John"
});

alert( bound.test ); // what will be the output? why?
alert( bound.test ); // qual vai ser a saída? por quê?
*/!*
```

Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@

The error occurs because `askPassword` gets functions `loginOk/loginFail` without the object.
O erro acontece porque `askPassword` recebe as funções `loginOk/loginFail` sem o objeto.

When it calls them, they naturally assume `this=undefined`.
Quando ele as chama, elas naturalmente assumem `this=undefined`.

Let's `bind` the context:
Vamos vincular (`bind`) o contexto:

```js run
function askPassword(ok, fail) {
Expand All @@ -30,14 +30,14 @@ askPassword(user.loginOk.bind(user), user.loginFail.bind(user));
*/!*
```

Now it works.
Agora funciona.

An alternative solution could be:
Uma solução alternativa poderia ser:
```js
//...
askPassword(() => user.loginOk(), () => user.loginFail());
```

Usually that also works and looks good.
Normalmente isso também funciona e fica bom.

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()`.
Porém, é um pouco menos confiável em situações mais complexas, onde a variável `user` pode mudar *depois* que `askPassword` é chamada, mas *antes* que o visitante responda e chame `() => user.loginOk()`.
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ importance: 5

---

# Fix a function that loses "this"
# Corrija uma função que perde o "this"

The call to `askPassword()` in the code below should check the password and then call `user.loginOk/loginFail` depending on the answer.
A chamada a `askPassword()` no código abaixo deveria verificar a senha e então chamar `user.loginOk/loginFail` dependendo da resposta.

But it leads to an error. Why?
Mas ela causa um erro. Por quê?

Fix the highlighted line for everything to start working right (other lines are not to be changed).
Corrija a linha destacada para que tudo comece a funcionar direito (as outras linhas não devem ser mudadas).

```js run
function askPassword(ok, fail) {
Expand Down
6 changes: 3 additions & 3 deletions 1-js/06-advanced-functions/10-bind/6-ask-partial/solution.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@


1. Either use a wrapper function, an arrow to be concise:
1. Ou use uma função de invólucro, uma função seta para ficar conciso:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Terminologia inconsistente: "função seta" aqui, mas o capítulo vizinho (12-arrow-functions) usa arrow function. Leitor vê dois termos para o mesmo conceito.

Suggested change
1. Ou use uma função de invólucro, uma função seta para ficar conciso:
1. Ou use uma função invólucro (wrapper), uma *arrow function* para ficar conciso:


```js
askPassword(() => user.login(true), () => user.login(false));
```

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Referente ambíguo: "o executa" concorda com user (masculino), dando a entender que se executa o objeto user. O original "runs it" se refere ao método.

Suggested change
```
Agora ela pega `user` das variáveis externas e chama o método da forma normal.


Now it gets `user` from outer variables and runs it the normal way.
Agora ela pega `user` das variáveis externas e o executa da forma normal.

2. Or create a partial function from `user.login` that uses `user` as the context and has the correct first argument:
2. Ou crie uma função parcial a partir de `user.login`, que usa `user` como contexto e tem o primeiro argumento correto:


```js
Expand Down
10 changes: 5 additions & 5 deletions 1-js/06-advanced-functions/10-bind/6-ask-partial/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ importance: 5

---

# Partial application for login
# Aplicação parcial para login

The task is a little more complex variant of <info:task/question-use-bind>.
A tarefa é uma variante um pouco mais complexa de <info:task/question-use-bind>.

The `user` object was modified. Now instead of two functions `loginOk/loginFail`, it has a single function `user.login(true/false)`.
O objeto `user` foi modificado. Agora, em vez de duas funções `loginOk/loginFail`, ele tem uma única função `user.login(true/false)`.

What should we pass `askPassword` in the code below, so that it calls `user.login(true)` as `ok` and `user.login(false)` as `fail`?
O que devemos passar para `askPassword` no código abaixo, para que ele chame `user.login(true)` como `ok` e `user.login(false)` como `fail`?

```js
function askPassword(ok, fail) {
Expand All @@ -30,5 +30,5 @@ askPassword(?, ?); // ?
*/!*
```

Your changes should only modify the highlighted fragment.
Suas mudanças devem modificar apenas o fragmento destacado.

Loading