Skip to content

Object methods, "this" #151

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

Merged
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,10 +1,10 @@
**Answer: an error.**
**Відповідь: помилка.**

Try it:
```js run
function makeUser() {
return {
name: "John",
name: "Іван",
ref: this
};
}
Expand All @@ -14,31 +14,31 @@ 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.
Це тому, що правила, які встановлюють `this`, не розглядають оголошення об’єкта. Важливий лише момент виклику метода.

Here the value of `this` inside `makeUser()` is `undefined`, because it is called as a function, not as a method with "dot" syntax.
Тут значення `this` всередині `makeUser()` є `undefined`, оскільки воно викликається як функція, а не як метод із синтаксисом "через крапку".

The value of `this` is one for the whole function, code blocks and object literals do not affect it.
Значення `this` є одним для всієї функції, блоки коду та літерали об’єктів на це не впливають.

So `ref: this` actually takes current `this` of the function.
Отже, `ref: this` дійсно бере значення `this` функції.

We can rewrite the function and return the same `this` with `undefined` value:
Ми можемо переписати функцію і повернути те саме `this` зі значенням` undefined`:

```js run
function makeUser(){
return this; // this time there's no object literal
return this; // цього разу немає літерала об’єкта
}

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.
Як бачите, результат `alert( makeUser().name )` збігається з результатом `alert( user.ref.name )` з попереднього прикладу.

Here's the opposite case:
Ось протилежний випадок:

```js run
function makeUser() {
return {
name: "John",
name: "Іван",
*!*
ref() {
return this;
Expand All @@ -49,7 +49,7 @@ function makeUser() {

let user = makeUser();

alert( user.ref().name ); // John
alert( user.ref().name ); // Іван
```

Now it works, because `user.ref()` is a method. And the value of `this` is set to the object before dot `.`.
Зараз це працює, оскільки `user.ref()` -- це метод. І значення `this` встановлюється для об'єкта перед крапкою `.`.
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,22 @@ importance: 5

---

# Using "this" in object literal
# Використання "this" в об’єктному літералі

Here the function `makeUser` returns an object.
Тут функція `makeUser` повертає об’єкт.

What is the result of accessing its `ref`? Why?
Який результат доступу до його `ref`? Чому?

```js
function makeUser() {
return {
name: "John",
name: "Іван",
ref: this
};
}

let user = makeUser();

alert( user.ref.name ); // What's the result?
alert( user.ref.name ); // Який результат?
```

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
# Створіть калькулятор

Create an object `calculator` with three methods:
Створіть об'єкт `calculator` з трьома методами:

- `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()` запитує два значення та зберігає їх як властивості об'єкта.
- `sum()` повертає суму збережених значень.
- `mul()` множить збережені значення і повертає результат.

```js
let calculator = {
// ... your code ...
// ... ваш код ...
};

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.
Рішення полягає у поверненні самого об’єкта з кожного виклику функції.

```js run demo
let ladder = {
Expand Down Expand Up @@ -26,7 +26,7 @@ let ladder = {
ladder.up().up().down().up().down().showStep(); // 1
```

We also can write a single call per line. For long chains it's more readable:
Ми також можемо написати один виклик функції на кожну лінію коду. Для довгих ланцюгів коду це читабельніше:

```js
ladder
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
# Ланцюг викликів

There's a `ladder` object that allows to go up and down:
Існує об'єкт `ladder`, що дозволяє підійматися вгору-вниз:

```js
let ladder = {
Expand All @@ -15,13 +15,13 @@ let ladder = {
down() {
this.step--;
},
showStep: function() { // shows the current step
showStep: function() { // показує поточний крок
alert( this.step );
}
};
```

Now, if we need to make several calls in sequence, can do it like this:
Тепер, якщо нам потрібно зробити кілька викликів послідовно, можна зробити це так:

```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:
Змініть код `up`, `down` і `showStep` так, щоб зробити доступним ланцюг викликів, наприклад:

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

Such approach is widely used across JavaScript libraries.
Такий підхід широко використовується в бібліотеках JavaScript.
Loading