Object methods, "this" by MykolaSopiha · Pull Request #151 · javascript-tutorial/uk.javascript.info
@@ -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` встановлюється для об'єкта перед крапкою `.`.
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` встановлюється для об'єкта перед крапкою `.`.