Ok, we have already talked about functions, objects, execution contexts. Now we will return to the last one.

this

As you remember during Creation Phase, Execution Context creates a special variable: this. Now we will take care of it to understand what it refers to and when it is used.

Another thing that you should remember is that even if our JavaScript file was empty, the Global Execution Context would be created.
Thanks to it we will gain access to a special variable: this, which in the browser will point to the window object.

It was just a reminder, and now let's take a look at some examples.

Do you know what will indicate this in both cases?

Each of them point to the same address in memory, our Global Object.
Although during the invocation of our code, 3 Execution Contexts were created, it is because the functions are lexically located in the Global Object, this will indicate to it.
If there is such a need, we can also check on the console whether our functions are actually visible using dot notation.

Now let's take a look at the example below.

As you can see, we created the object. In it, we find a method called the method. Its task is simple. We want the console to return this.
What do you think will be represented by the this variable?

Exactly, in this case, this variable refers to the object in which it is used. Exactly the same as in the previous case, where the object was Global Object.
Thanks to variable this, we can modify, among other things, other variables in the object.
Let's look at the code below.

As you can see by using the this variable, which points to the object and the dot notation, we can change its value.

Now, let's modify it even more. Let's create a function in a function. We can, why not?

What do we get in the second console.log?

The answer will surprise you.

Well, how is it possible? Theoretically, it should still refer to the object, the myObject.
In addition, if we check in the console and call window.name to our surprise we will get this:

This is a situation that is considered by many to be a JavaScript engine bug.
So what do we do if we have a similar situation but we want to relate in a way as it should be, that is to the object through the variable this?
We can use a patter that is quite commonly used.

As you can see in line 4, we precisely defined what we expect from using the self and what address it should indicate in the memory.
It is also worth noting that because when the code is executed in the Execution Context of the changeName function, the engine can not find the self variable.
Thanks to how Scope works in JavaScript, we know that the engine will start looking "down". There, however, he gets clear instructions that the self should be an address to the myObject object.

Next Post

I will talk about arguments and spread.