> For the complete documentation index, see [llms.txt](https://aleksandra-hrevtsova.gitbook.io/senior-front-end-javascript/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://aleksandra-hrevtsova.gitbook.io/senior-front-end-javascript/obekty/this-kontekst-ispolneniya.md).

# this - контекст исполнения

## Обращение к свойству внутри метода

Если метод объекта должен работать со значением свойства объекта, то можно обращаться к такому свойству, как обычно, через объект.

Но, наша задача - создание переиспользуемого кода, то есть, наши методы должны уметь работать не только в привязке к объекту, которому принадлежат, но с другими объектами, у которых хранятся подобные данные и свойства, как у текущего объекта.

Например, у меня есть объект пользователя с набором методов для работы с его свойствами имени, возраста, почты и так далее.

Я могу получать сколько угодно новых объектов пользователей, но им уже не нужно иметь такой же набор методов и тратить на это заветную память. Мы можем использовать методы нашего основного объекта пользователя в контексте всех остальных подобных объектов, главное, чтобы внутри методов, обращением к свойствам было через this, а не через конкретное имя объекта.

```
const user = {
    name: 'user',
    toGreetUser(greeting, info) {
        return `Hello ${this.name}! ${greeting} ${info}`;
    }
}

user.toGreetUser('We are glad to see you!', 'My name is Bot');
```

А как можно использовать метод toGreetUser(), который принадлежит объекту user для других объектов?

Нужно `прикалывать` контекст исполнения в новом объекте. Для этого существуют методы: `call`, `apply` & `bind`. Call & apply - используется в мгновенных вызовах, bind - используется, если метод передаем в качестве колбека, который будет вызван не мгновенно, а при вызове функции, в которую передан.

Отличие `call` & `apply` заключается в передаче аргументов, после указания объекта, в контексте которого должен быть вызван метод.

Call ожидает аргументы просто перечисленные через запятую после объекта.

Apply ожидает все аргументы, собранные в массив `[]`.

Bing, как call, только для колбеков.

```
const newUser = {
    name: 'Sandra',
}

user.toGreetUser.call(newUser, 'We are glad to see you!', 'My name is Bot')
user.toGreetUser.apply(newUser, ['We are glad to see you!', 'My name is Bot'])

function authUser(callback){
    callback()
};

let result = authUser(
  user.toGreetUser.bind(newUser, 'We are glad to see you!', 'My name is Bot')
);
console.log(result);
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://aleksandra-hrevtsova.gitbook.io/senior-front-end-javascript/obekty/this-kontekst-ispolneniya.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
