GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Function binding by vplentinax · Pull Request #206 · javascript-tutorial/es.javascript.info

Function binding #206

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
vplentinax merged 3 commits into javascript-tutorial:master from vplentinax:binding
Jun 3, 2020

Uh oh!

There was an error while loading. Please reload this page.

Merged

Function binding #206

Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
3 commits
Select commit Hold shift + click to select a range
70d8d94
bind
vplentinax May 25, 2020
d8070d3
corrections
vplentinax Jun 2, 2020
e2b552a
Merge branch 'master' into binding
vplentinax Jun 3, 2020
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view

There are no files selected for viewing

6 changes: 3 additions & 3 deletions 6 1-js/06-advanced-functions/10-bind/2-write-to-object-after-bind/solution.md
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
The answer: `null`.
Respuesta: `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.
El contexto de una función enlazada es fijo. Simplemente no hay forma de cambiarlo más.

So even while we run `user.g()`, the original function is called with `this=null`.
Entonces, incluso mientras ejecutamos `user.g()`, la función original se llama con `this = null`.
4 changes: 2 additions & 2 deletions 4 1-js/06-advanced-functions/10-bind/2-write-to-object-after-bind/task.md
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ importance: 5

---

# Bound function as a method
# Función enlazada como método

What will be the output?
¿Cuál será el resultado?

```js
function f() {
Expand Down
6 changes: 3 additions & 3 deletions 6 1-js/06-advanced-functions/10-bind/3-second-bind/solution.md
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
The answer: **John**.
Respuesta: **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.
El objeto exótico [bound function](https://tc39.github.io/ecma262/#sec-bound-function-exotic-objects) devuelto por `f.bind(...)` recuerda el contexto (y los argumentos si se proporcionan) solo en el momento de la creación.

A function cannot be re-bound.
Una función no se puede volver a vincular.
6 changes: 3 additions & 3 deletions 6 1-js/06-advanced-functions/10-bind/3-second-bind/task.md
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ importance: 5

---

# Second bind
# Segundo enlace

Can we change `this` by additional binding?
¿Podemos cambiar `this` por un enlace adicional?

What will be the output?
¿Cuál será el resultado?

```js no-beautify
function f() {
Expand Down
4 changes: 2 additions & 2 deletions 4 1-js/06-advanced-functions/10-bind/4-function-property-after-bind/solution.md
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
The answer: `undefined`.
Respuesta: `undefined`.

The result of `bind` is another object. It does not have the `test` property.
El resultado de `bind` es otro objeto. No tiene la propiedad `test`.

7 changes: 4 additions & 3 deletions 7 1-js/06-advanced-functions/10-bind/4-function-property-after-bind/task.md
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ importance: 5

---

# Function property after bind
# Propiedad de función después del enlace

There's a value in the property of a function. Will it change after `bind`? Why, or why not?

Hay un valor en la propiedad de una función. ¿Cambiará después de `bind`? ¿Por qué sí o por qué no?

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

alert( bound.test ); // what will be the output? why?
alert( bound.test ); // ¿Cuál será la salida? ¿por qué?
*/!*
```

16 changes: 10 additions & 6 deletions 16 1-js/06-advanced-functions/10-bind/5-question-use-bind/solution.md
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@

The error occurs because `ask` gets functions `loginOk/loginFail` without the object.
El error se produce porque `ask` obtiene las funciones `loginOk/loginFail` sin el objeto.

When it calls them, they naturally assume `this=undefined`.
Cuando los llama, asumen naturalmente `this = undefined`.

Let's `bind` the context:
Vamos a usar `bind` para enlazar el contexto:

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

Now it works.
Ahora funciona.

An alternative solution could be:
Una solución alternativa podría ser:
```js
//...
askPassword(() => user.loginOk(), () => user.loginFail());
```

Usually that also works and looks good.

Por lo general, eso también funciona y se ve bien.

Aunque es un poco menos confiable en situaciones más complejas donde la variable `user` podría cambiar *después* de que se llama a `askPassword`, *antes* de que el visitante responde y llame a `() => user.loginOk ()`.


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()`.
9 changes: 5 additions & 4 deletions 9 1-js/06-advanced-functions/10-bind/5-question-use-bind/task.md
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@ importance: 5

---

# Fix a function that loses "this"

The call to `askPassword()` in the code below should check the password and then call `user.loginOk/loginFail` depending on the answer.
# Arreglar una función que perdió "this"

But it leads to an error. Why?
La llamada a `askPassword()` en el código a continuación debe verificar la contraseña y luego llamar a `user.loginOk/loginFail` dependiendo de la respuesta.

Fix the highlighted line for everything to start working right (other lines are not to be changed).
Pero lleva a un error. ¿Por qué?

Arregle la línea resaltada para que todo comience a funcionar correctamente (no se deben cambiar otras líneas).

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


1. Either use a wrapper function, an arrow to be concise:

1. Utilice una función wrapper (envoltura), de tipo arrow (flecha) para ser conciso:

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

Now it gets `user` from outer variables and runs it the normal way.

2. Or create a partial function from `user.login` that uses `user` as the context and has the correct first argument:
Ahora obtiene `user` de variables externas y lo ejecuta de la manera normal.

2. O cree una función parcial desde `user.login` que use `user` como contexto y tenga el primer argumento correcto:



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

---

# Partial application for login

The task is a little more complex variant of <info:task/question-use-bind>.
# Aplicación parcial para inicio de sesión

The `user` object was modified. Now instead of two functions `loginOk/loginFail`, it has a single function `user.login(true/false)`.
La tarea es una variante un poco más compleja de <info:task/question-use-bind>.

El objeto `user` fue modificado. Ahora, en lugar de dos funciones `loginOk/loginFail`, tiene una sola función `user.login(true/false) `.

¿Qué deberíamos pasar a `askPassword` en el código a continuación, para que llame a `user.login(true)` como `ok` y `user.login(false)` como `fail`?

What should we pass `askPassword` in the code below, so that it calls `user.login(true)` as `ok` and `user.login(false)` as `fail`?

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

Your changes should only modify the highlighted fragment.

Sus cambios solo deberían modificar el fragmento resaltado.


Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.