Skip to content
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 our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Object methods, "this" #343

Merged
merged 16 commits into from
Aug 16, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
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,6 +1,6 @@
**Answer: an error.**
**Respuesta: un error.**

Try it:
Pruébalo:
```js run
function makeUser() {
return {
Expand All @@ -11,29 +11,29 @@ function makeUser() {

let user = makeUser();

alert( user.ref.name ); // Error: Cannot read property 'name' of undefined
alert( user.ref.name ); // Error: No se puede leer la propiedad 'name' de undefined
```

That's because rules that set `this` do not look at object definition. Only the moment of call matters.
Esto es porque porque las reglas que establecen el `this` no buscan en la definición del objeto. Solamente importa el momento en que se llama.
joaquinelio marked this conversation as resolved.
Show resolved Hide resolved
joaquinelio marked this conversation as resolved.
Show resolved Hide resolved

Here the value of `this` inside `makeUser()` is `undefined`, because it is called as a function, not as a method with "dot" syntax.
Aquí el valor de `this` dentro de `makeUser()` es `undefined`, porque es llamado como una función, no como un método con sintaxis de punto.

The value of `this` is one for the whole function, code blocks and object literals do not affect it.
El valor de `this` es uno para la función entera, bloques de código y objetos literales no lo afectan.
joaquinelio marked this conversation as resolved.
Show resolved Hide resolved
Copy link
Collaborator

Choose a reason for hiding this comment

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

Suggested change
El valor de `this` es uno para la función entera, bloques de código y objetos literales no lo afectan.
El valor de `this` es uno para la función entera. Bloques de código y objetos literales no lo afectan.

Funciona bien así como dos oraciones independientes en el mismo párrafo y pienso que se entiende mejor. Si lo leo con la coma me voy de corrido y pienso que es "función entera, bloques de código y objetos literales" hasta que mi cerebro hace corto circuito al encontrarse con "no lo afectan".

Copy link
Contributor

Choose a reason for hiding this comment

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

@maksumi la coma es justamente de pausa en este caso. No se recomiendo usa punto para dar pausa o separar oraciones pequeñas.

Copy link
Member Author

Choose a reason for hiding this comment

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

creo qu amerita un " ; " !!!
si está mal no me importa.

Creo que se lee bien en una oracion si lee con el ritmo adecuado,
tambien reo que se puede poner en dos oraciones aunque se corte un poquito

pero asi no hay duda:
El valor de this es uno para la función entera; bloques de código y objetos literales no lo afectan.

podria haber puesto
fun entera, ni bloquess ni lieterales...
fun entera (biques y leterales....)
muy feo.


So `ref: this` actually takes current `this` of the function.
Entonces `ref: this` en realidad toma el `this` actual de la función.

We can rewrite the function and return the same `this` with `undefined` value:
Podemos reescribir la función y devolver el mismo `this` con valor `undefined`:

```js run
function makeUser(){
return this; // this time there's no object literal
return this; // esta vez no hay objeto literal
}

alert( makeUser().name ); // Error: Cannot read property 'name' of undefined
alert( makeUser().name ); // Error: No se puede leer la propiedad 'name' de undefined
```
As you can see the result of `alert( makeUser().name )` is the same as the result of `alert( user.ref.name )` from the previous example.
Como puedes ver el resultado de `alert( makeUser().name )` es el mismo que el resultado de `alert( user.ref.name )` del ejemplo anterior.

Here's the opposite case:
Aquí está el caso opuesto:

```js run
function makeUser() {
Expand All @@ -52,4 +52,4 @@ let user = makeUser();
alert( user.ref().name ); // John
```

Now it works, because `user.ref()` is a method. And the value of `this` is set to the object before dot `.`.
Ahora funciona, porque `user.ref()` es un método. Y el valor de `this` es establecido al del objeto delante del punto `.`.
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ importance: 5

---

# Using "this" in object literal
# Uso de "this" en un objeto literal
joaquinelio marked this conversation as resolved.
Show resolved Hide resolved

Here the function `makeUser` returns an object.
Aquí la función `makeUser` devuelve un objeto.

What is the result of accessing its `ref`? Why?
¿Cuál es el resultado de acceder a su `ref`? ¿Por qué?

```js
function makeUser() {
Expand All @@ -18,6 +18,6 @@ function makeUser() {

let user = makeUser();

alert( user.ref.name ); // What's the result?
alert( user.ref.name ); // ¿Cuál es el resultado?
```

12 changes: 6 additions & 6 deletions 1-js/04-object-basics/04-object-methods/7-calculator/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@ importance: 5

---

# Create a calculator
# Crea una calculadora

Create an object `calculator` with three methods:
Crea un objeto `calculator` con tres métodos:

- `read()` prompts for two values and saves them as object properties.
- `sum()` returns the sum of saved values.
- `mul()` multiplies saved values and returns the result.
- `read()` pide dos valores y los almacena como propiedadess de objeto.
- `sum()` devuelve la suma de los valores almacenados.
- `mul()` multiplica los valores almacenados y devuelve el resultado.

```js
let calculator = {
// ... your code ...
// ... tu código ...
};

calculator.read();
Expand Down
12 changes: 6 additions & 6 deletions 1-js/04-object-basics/04-object-methods/8-chain-calls/task.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ importance: 2

---

# Chaining
# Encadenamiento

There's a `ladder` object that allows to go up and down:
Hay un objeto escalera `ladder` que permite subir y bajar:
joaquinelio marked this conversation as resolved.
Show resolved Hide resolved

```js
let ladder = {
Expand All @@ -15,13 +15,13 @@ let ladder = {
down() {
this.step--;
},
showStep: function() { // shows the current step
showStep: function() { // muestra el peldaño actual
alert( this.step );
}
};
```

Now, if we need to make several calls in sequence, can do it like this:
Ahora, si necesitamos hace varios llamados en secuencia, podemos hacer algo como esto:
joaquinelio marked this conversation as resolved.
Show resolved Hide resolved

```js
ladder.up();
Expand All @@ -30,10 +30,10 @@ ladder.down();
ladder.showStep(); // 1
```

Modify the code of `up`, `down` and `showStep` to make the calls chainable, like this:
Modifica el código de "arriba" `up`, "abajo" `down` y "mostrar peldaño" `showStep` para hacer los llamados encadenables como esto:

```js
ladder.up().up().down().showStep(); // 1
```

Such approach is widely used across JavaScript libraries.
Tal enfoque es ampliamente usado entre las librerías JavaScript.
Loading