Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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.

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

Already on GitHub?Sign in to your account

Merged
vplentinax merged 3 commits intojavascript-tutorial:masterfromvplentinax:binding
Jun 3, 2020
Merged
Show file tree
Hide file tree
Changes fromall 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
View file
Open in desktop
Original file line numberDiff line numberDiff 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 justnoway to further change it.
El contexto de una función enlazada es fijo. Simplementenohay forma de cambiarlo más.

So even while we run`user.g()`,theoriginalfunction is called with`this=null`.
Entonces, incluso mientras ejecutamos`user.g()`,la funciónoriginalse llama con`this =null`.
View file
Open in desktop
Original file line numberDiff line numberDiff 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
View file
Open in desktop
Original file line numberDiff line numberDiff 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 deletions1-js/06-advanced-functions/10-bind/3-second-bind/task.md
View file
Open in desktop
Original file line numberDiff line numberDiff 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
View file
Open in desktop
Original file line numberDiff line numberDiff 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`.

View file
Open in desktop
Original file line numberDiff line numberDiff 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é?
*/!*
```

View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@

The erroroccurs because`ask`gets functions`loginOk/loginFail`without the object.
El errorse 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()`.
View file
Open in desktop
Original file line numberDiff line numberDiff 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
View file
Open in desktop
Original file line numberDiff line numberDiff 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 deletions1-js/06-advanced-functions/10-bind/6-ask-partial/task.md
View file
Open in desktop
Original file line numberDiff line numberDiff 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

[8]ページ先頭

©2009-2025 Movatter.jp