‘this’ in JavaScript — learn in practice

Let’s look at the example below

Answers for the impatient

A Lit a Bit of Theory

Unlike many other programming languages, the keyword this in javascript does not bind to the object, but depends on the context of the call. For simplicity of understanding, we will consider examples with reference to the browser, where the global object is window.

#1 — Simple function call

In this case, this inside the function f is equal to the global object (for example, in the browser it is window).

Self-invoking functions work in exactly the same way.

#2 — In the constructor

When a function is called using the new keyword, the function acts as a constructor, and in this case this indicates the object being created.

#3 — In the object method

If the function is started as an object property, then this will reference this object. It does not matter where this function came from in the object, the main thing is how it is called, namely what object is before the function is called:

#4 — Methods apply & call

The apply and call methods allow you to specify the context for the function to be executed. The difference between apply and call-only in the way of passing parameters to a function. The first parameter of both functions defines the context of the execution of the function (what this will be).

The difference in apply / call



Back to the first example:

Let us apply the results of Theory part to the problem given at the beginning of the topic. Again, for simplicity, we will consider examples for a browser where the global object is a window.

1. f()

In result we have 3

2. new f()

In result we have 5

3. obj.m()

In result we have 4

4. new obj.m()

In result we have undefined

5. f.call(f)

In result we have 5

6. obj.m.call(f)

In result we have 5

Note: If this example is considered separately from the rest, then the log will not be 5, but undefined.

Like what you read? Give Alla Gorik a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.