Skip to content
Merged
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,6 +1,6 @@
**Answer: an error.**
**Resposta: um erro.**

Try it:
Experimente:
```js run
function makeUser() {
return {
Expand All @@ -14,26 +14,26 @@ let user = makeUser();
alert( user.ref.name ); // Error: Cannot read property 'name' of undefined
```

That's because rules that set `this` do not look at object definition. Only the moment of call matters.
Isso é porque as regras que definem `this` não olham para a definição do objeto. Apenas o momento da chamada importa.

Here the value of `this` inside `makeUser()` is `undefined`, because it is called as a function, not as a method with "dot" syntax.
Aqui o valor de `this` dentro de `makeUser()` é `undefined`, porque ela é chamada como uma função, não como um método com sintaxe de "ponto".

The value of `this` is one for the whole function, code blocks and object literals do not affect it.
O valor de `this` é único para toda a função, blocos de código e literais de objeto não o afetam.

So `ref: this` actually takes current `this` of the function.
Então `ref: this` na verdade obtém o `this` atual da função.

We can rewrite the function and return the same `this` with `undefined` value:
Podemos reescrever a função e retornar o mesmo `this` com valor `undefined`:

```js run
function makeUser(){
return this; // this time there's no object literal
return this; // desta vez não há literal de objeto
}

alert( makeUser().name ); // Error: Cannot read property 'name' of 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 você pode ver, o resultado de `alert( makeUser().name )` é o mesmo que o resultado de `alert( user.ref.name )` do exemplo anterior.

Here's the opposite case:
Aqui está o caso oposto:

```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 `.`.
Agora funciona, porque `user.ref()` é um método. E o valor de `this` é definido como o objeto antes do ponto `.`.
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ importance: 5

---

# Using "this" in object literal
# Usando "this" em literal de objeto

Here the function `makeUser` returns an object.
Aqui a função `makeUser` retorna um objeto.

What is the result of accessing its `ref`? Why?
Qual é o resultado de acessar seu `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 ); // Qual é o 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
# Crie uma calculadora

Create an object `calculator` with three methods:
Crie um objeto `calculator` com três métodos:

- `read()` prompts for two values and saves them as object properties with names `a` and `b` respectively.
- `sum()` returns the sum of saved values.
- `mul()` multiplies saved values and returns the result.
- `read()` solicita dois valores e os salva como propriedades do objeto com os nomes `a` e `b` respectivamente.
- `sum()` retorna a soma dos valores salvos.
- `mul()` multiplica os valores salvos e retorna o resultado.

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

calculator.read();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
The solution is to return the object itself from every call.
A solução é retornar o próprio objeto de cada chamada.

```js run demo
let ladder = {
Expand All @@ -23,10 +23,10 @@ let ladder = {
}
};

ladder.up().up().down().showStep().down().showStep(); // shows 1 then 0
ladder.up().up().down().showStep().down().showStep(); // mostra 1 depois 0
```

We also can write a single call per line. For long chains it's more readable:
Também podemos escrever uma única chamada por linha. Para cadeias longas é mais legível:

```js
ladder
Expand Down
18 changes: 9 additions & 9 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,26 +2,26 @@ importance: 2

---

# Chaining
# Encadeamento

There's a `ladder` object that allows you to go up and down:
Existe um objeto `ladder` que permite subir e descer:

```js
let ladder = {
step: 0,
up() {
up() {
this.step++;
},
down() {
down() {
this.step--;
},
showStep: function() { // shows the current step
showStep: function() { // mostra o degrau atual
alert( this.step );
}
};
```

Now, if we need to make several calls in sequence, we can do it like this:
Agora, se precisarmos fazer várias chamadas em sequência, podemos fazer assim:

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

Modify the code of `up`, `down`, and `showStep` to make the calls chainable, like this:
Modifique o código de `up`, `down` e `showStep` para tornar as chamadas encadeáveis, assim:

```js
ladder.up().up().down().showStep().down().showStep(); // shows 1 then 0
ladder.up().up().down().showStep().down().showStep(); // mostra 1 depois 0
```

Such an approach is widely used across JavaScript libraries.
Essa abordagem é amplamente usada em bibliotecas JavaScript.
Loading