The Complete Beginner’s Guide to ‘this’ in Javascript

The Complete Beginner’s Guide to ‘this’ in Javascript


  • Share on Pinterest

In order to comprehend the meaning of the keyword ‘this’ in javascript, you must first understand the meaning of the word context in the actual world.

As you may know, the word context refers to the underlying concepts and facts which are required to comprehend an idea or statement. 

For example, if you take a look at a dictionary for the definition of the word set, you will find that there is a huge list of different meanings of this word that depends on the situation under which the word is used.

That situation is the context that will help you to grasp the full meaning of the word.

But how is this related to the ‘this’ keyword in javascript? 

Well, the meaning of ‘this’ in javascript depends on the context of a function call (invocation).

In javascript language, there are the following different function invocation types:

  1. Function invocation
  2. Method invocation
  3. Constructor invocation
  4. Indirect invocation

For each invocation type, the ‘this’ keyword behaves differently. 

Furthermore, another parameter that affects the execution context is the usage of the strict mode in javascript.

In this article, we are going to examine the meaning of the keyword ‘this’ in javascript depending on the context a.k.a the function invocation type. 

Function invocation

The term a function invocation refers to the execution of the code that the body of a function includes. An equivalent term of the function invocation is the call of a function.

As you may know, the javascript engine executes a code block through two phases.

The first phase is called Creation Phase and the second Execution Phase

During the Creation Phase, the javascript engine creates a Global Execution Context and uses it to store the function declarations in the memory heap and variables. The initial values of each function and variable are equal to undefined.

After the completion of the creation phase, the Execution Phase takes place. This is the moment that the code starts to run in the context that was formed in the Creation Phase

So what does all this has to do with the ‘this’ in javascript? 

The ‘this’ keyword is referring to the Global Execution Context that was created during the Creation Phase

When you execute the code in a browser, the Global Execution Context will refer to the window object.

On the other hand, if you execute the code in a Node JS environment the global context will be the global object instead of the window object.

Let’s see an example of code.

See the Pen
Untitled
by codebitshub (@codebitshub)
on CodePen.

At the time the javascript engine calls the foo() function it sets this to the window context.

Similar to the above if you use the ‘this’ keyword outside of any function scope it will equal the window object.

The strict mode in a function invocation

Since ECMAScipt 5, the ‘strict mode‘ of javascript is supported which is a restricted variant of javascript. The strict mode has intentionally different semantics from normal code and what it does, is to provide stronger error checking and perform optimizations.

In order to use it, you have to add the directive ‘use strict’ at the top of a function body. It is important to remember that once the ‘strict mode‘ is enabled it will affect the execution context and this value will be undefined in a function invocation.

Let’s see an example.

See the Pen
Strict mode function invocation
by codebitshub (@codebitshub)
on CodePen.

Additionally, when you enable the ‘strict mode‘ at the top of a function body, it will affect the scope for any nested function too.

See the Pen
Untitled
by codebitshub (@codebitshub)
on CodePen.

Finally, it is possible to use both ‘strict mode‘ and ‘non-strict mode‘ in different functions in the same javascript file. 

Let’s see an example.

See the Pen
Untitled
by codebitshub (@codebitshub)
on CodePen.

Method invocation (implicit binding)

You can save a function as a property in an object too. This type of function is called a method. In order to access a method, you will have to use a property accessor.

A method invocation takes place when you access a method and add next to it an open parenthesis any arguments, and finally a close parenthesis.

The keyword ‘this’ in this case will refer to the object that owns the method. 

Let’s see an example.

See the Pen
Method invocation
by codebitshub (@codebitshub)
on <

The same is true in the cases that an object inherits a method from its prototype or the ECMAScript 2015 class syntax is used. In this case, the ‘this‘ keyword will refer to the object that owns the method which will be the object itself.

Common misunderstandings with methods

In this section, I will mention two common errors that you possibly could face working with methods.

‘this’ in inner function of an object method

Let’s see an example.

See the Pen
Untitled
by codebitshub (@codebitshub)
on CodePen.

You may expect the ‘this‘ keyword to be equal to myObject but in this case, this is not true.  Since the function testThis is not a method but a function that is declared inside the myObject object, its context will be the global context even if the logs function context is the myObject object. 

If you want to change the context of the testThis function you will have to use one of the following ways that will bind the function to the desired context. You could use the apply method, the call method, or an arrow function instead.

See the Pen
Untitled
by codebitshub (@codebitshub)
on CodePen.

Extracting a method from an object

Another common misunderstanding is to extract a method from an object and assign it to a variable. The function context will be the global context in this case too.

Let’s see an example.

See the Pen
Extracting a method from an object
by codebitshub (@codebitshub)
on CodePen.

Similar to the previous case, you can change the context of the testThis function if you use one of the call or apply methods.

See the Pen
change context with call method
by codebitshub (@codebitshub)
on CodePen.

Indirect invocation (explicit binding)

As you may know, Functions in javascript are first-class objects. The type of function object is Function. Since it is an object, it inherits all the methods and properties from its prototype.

In the list of methods that are inherited, you can see that there are two methods that are related to the context the function will be called.

These are the methods apply and call

The method apply accepts as the first argument the context for the function invocation and as the second argument an array of arguments that are passed to the called function.

Likewise, the method call accepts as the first argument the context that will be used for the function invocation and a list of arguments that are passed to the called function.

This way of a function invocation through the methods apply and call is called indirect invocation.

Let’s see an example.

See the Pen
indirect function invocation
by codebitshub (@codebitshub)
on CodePen.

You can use this kind of invocation when you need to call a function in a specific context.

Another useful use case could be to chain constructors in the same context .

See the Pen
chain constructors
by codebitshub (@codebitshub)
on

You can see more information about the call function here.

Constructor invocation

One of the ways to create an Object in javascript is with the usage of a constructor function.

The constructor will create a new object and initialize its methods and properties with any data are given in the arguments. 

In order to use the function constructor method, you will have to use the new keyword.

In this case, the ‘this’ keyword will refer to the object when the object is created.

Let’s see an example.

See the Pen
Untitled
by codebitshub (@codebitshub)
on CodePen.

The directive new Foo(Hello’) makes a constructor invocation and passes the string ‘Hello’ to the constructor.

Then the constructor function will create a new Object named myObject. 

Inside the constructor function, the context is the Foo function object. As you can see in the logs after you access the property hello of the object myObject it will have the value ‘Hello’.

What is happening is that the javascript engine creates an empty object (Foo) and makes it the context of the constructor method. 

Next, it uses this empty object to populate any properties and methods and assigns them to the myObject object.

You can apply a similar logic using the class syntax. Let’s see the above code with the class syntax.

See the Pen
this in Class
by codebitshub (@codebitshub)
on CodePen.

Note: it is considered good practice to check the context of an object in a function constructor. This will protect you from errors like forgetting the use of the new keyword.

In this case, the context would be the global object.

See the Pen
context check
by codebitshub (@codebitshub)
on CodePen.

Extra bits

I could not omit from this article to mention two important factors that are related to the usage of ‘this’ in javascript. These are the bound functions and the arrow functions.

Bound functions

You can create a bound function with the usage of the bind method. The first argument of the bind method is the context that the function will use.

The bind method will create and return the bound function that will be executed in the predefined context.

Let’s see an example.

See the Pen
Bound Functions
by codebitshub (@codebitshub)
on CodePen.

Note: you can pass any arguments in the bound function as normally you would do.

Finally, I have to mention that the bind method creates a permanent context to the object and cannot be changed even with using the call/apply methods.

The only way to change an already bound context is by using the constructor function of the object with the new keyword.

Let’s see an example.

See the Pen
Bound functions change context
by codebitshub (@codebitshub)
o

Arrow functions

Arrow functions are a compact alternative to normal functions. An arrow function resolves its context lexically, which means that doesn’t create its own context. Instead, it inherits the context from the place you define it.

Let’s see an example.

See the Pen
arrow function
by codebitshub (@codebitshub)
on CodePen.

In the code example above the logContext function is an arrow function where it binds the global object to the context which is the window object.

Let’s see another example.

See the Pen
arrow function in nested method
by codebitshub (@codebitshub)
on CodePen.

In this example, we are using an arrow function to bind the context of the function testThis to myObject lexically.

If we were using a normal function, then the context of the function testThis would be the window object as we already saw in the section Common misunderstanding with methods. 

So the usage of an arrow function, in this case, is an alternative to using one of the call/apply methods

Note: The context of an arrow function is bound lexically and you cannot modify it even when using the apply/call methods.

Finally, arrow functions have some restrictions compared to normal functions. 

Below is a shortlist of these restrictions as they are mentioned in the Mozilla documentation

Summary

Let’s summarize what we discussed in this article. Below is a shortlist of the meaning of the keyword ‘this‘ in javascript that you should remember. 

Keep in mind that in order for you to have a deeper understanding of what ‘this‘ means in javascript you should think of how a function is invoked and for arrow functions what is ‘thisinside the outer function where the arrow function is declared.

Function invocation 

 →The ‘this‘ keyword will refer to the Global Execution Context. 

Method invocation 

→  The keyword ‘this‘ in this case will refer to the object that owns the method. 

Indirect invocation (apply/call methods) 

→ The keyword ‘this‘ in this case will refer to the object that is passed as the first argument in the methods call/apply. 

Constructor invocation 

→ In this case, the ‘this‘ keyword will refer to the object when the object is created.

Bound Functions 

→The keyword ‘this‘ in this case will refer to the object that is passed in the bind method.

Arrow functions

→The keyword ‘this‘ in this case will be resolved lexically and will refer to the context of the outer function where the arrow function is declared.

Happy coding!

LET’S KEEP IN TOUCH!

We’d love to keep you updated with our latest news and offers 😎

We don’t spam! Read our privacy policy for more info.