This in JavaScript

this” in JavaScript is an object. Every JavaScript function gets a copy of this (except arrow functions). Its value does not depend on where we declare it but on how we invoke it. There are four ways in which we can invoke a function. They are Function invocation, method invocation, Constructor invocation & Explicit invocation. Each of these invocations sets the value of this differently. This tutorial will dive deep into this in JavaScript and learn more about it.

What is “this” in Javascript

Take a look at the following person object. It contains the method sayHello. How do we get to the person’s name from within sayHello?

We use “this” keyword to access the person object.

Inside the sayHello function, the this keyword refers to the person object. Using this keyword, we can refer to all properties and methods of the person object inside the sayHello function.

We say this is bound to the person object inside the sayHello function.

this is an object to which function is bound to in the run time. The run-time binding of a function can change depending on how we invoke it. If there is no binding is found, then it defaults to the global object in nonstrict mode and undefined in strict mode.

Why “this” in JavaScript is so Confusing

In languages like c#, java, etc., this always points to the current class instance to which the method belongs. This is very intuitive and easy to grasp. The methods are bound to the class. You cannot change those bindings.

But there is one critical difference between functions in JavaScript and those in c# or Java. In JavaScript, functions are objects. They are not bound to anything. So, you can assign them to another variable, pass them around, etc.

For example, look at the following example.

The obj object declares the foo function and becomes the obj‘s method. When we invoke the foo function using obj.foo(), it prints the value of a (i.e., 10) from the obj and not from the global value of a. Here this inside the foo points to the obj itself. This is precisely how this works in C# & Java.

In the following example, we copy foo to another variable, boo. Now boo also points to the foo function, but it is not associated with the obj.

When we invoke boo, this points to the global object rather than foo. That is why it prints 1 instead of 10.

We can also assign the function as the property of another object. The following example attaches foo to another object, obj2. When we invoke obj2.foo(), this of the foo points to obj2.

So when you declare a function, you will never be sure what would be its “this". Because it never depends on where you declare it. But it depends on how you use it. The same function invoked differently gets different values for this.

This outside a function

The value of this outside of a function is always the global object.

The global object always exists in JavaScript applications. But what value it takes depends on where we run our app.

Inside the browser, the global object is window, while in NodeJS it is an object named global. The value does not depend on strict mode.

For Example, the following code returns window when run on a web browser.

How to identify this in Javascript

Value of “this” inside a function depends on how & where we invoke the function and whether the strict mode is enabled or not.

There are four ways in which you can invoke a function. They are

  1. Function Invocation
  2. Method Invocation
  3. Constructor invocation
  4. Explicit invocation

Each of the above Invocations sets the value of this differently. In the case of function invocations, the Strict Mode also affects the value of this.

Function Invocation or Default Binding

When we invoke a function as a standalone function (not as a property of an object), then we call that function Invocation.

In a function invocation this is bound to the global object in “not strict” mode. But if we use “strict” mode this is always null.

The window object is the global object in the web browser, while in NodeJs an object called globalThis is the global object

Invoking a Function expression.

But in a strict mode, this is undefined

You can also use use strict inside the function, but it must be at the beginning of a function.

Method Invocation (Implicit Binding)

The method is the function that we declare as the property of an object. When we invoke the method using the property accessor ( using dot or [] ), we call it method invocation.

In a method invocation, the object that invokes the method becomes the this of the method.

The following codes are examples of method invocation.

The last level of the object becomes this. In the following chained call foo comes last. Hence it becomes this.

The getName method inside foo, boo & bar refers to the global getName function.

Remember dot is not the only way to invoke a method. You can also make use of a bracket.

Inner function looses this binding

In the following example, we attach the outer function as method to obj object. Inside the outer function, we have inner function.

We invoke the outer function as method invocation (obj.outer()). Hence obj becomes the this of the outer function.

But inside the outer function, we invoke the inner function using the function invocation. Hence it gets the window object as its this

Workaround for the inner function

There is a simple way by which we can make the Inner function to access this from the outer function.

To do that create a local variable in the outer function. Name it as that. Assign this to that. Now you can access the that variable in the inner function

Separate method from the object

In the following example, we assign obj.testFunction() to a variable fn. The fn variable contains the reference to the testFunction.

When we invoke the testFunction using the method invocation (i.e., obj.testFunction()), the obj becomes the this of the testFunction.

But when we invoke it using the function invocation (i.e., fn()), then the window becomes the this of testFunction.

But we can force the outer function to use the obj as this by using the method bind. This is called explicit binding. We will talk about it later

Constructor Invocation or New Binding

We can also invoke a function using a new Operator. We usually use the new operator on a Constructor function to create a new object. But we can use the new operator on any function.

If the function is invoked with new keyword, then the this is a new object

If you invoke a function without new keyword it will be a function invocation. In that case the this will be global object

You can read more about constructor function and new operator

Explicit Binding

We can also set the value of this explicitly. i.e. we pass the value of this, when we invoke the function overriding the JavaScript generated this. This is useful when we make use of the callback functions

There are three methods that allow us the set the this of an object. All of them are available in the function.prototype object.

  1. Call
  2. Apply
  3. Bind

Call

The call() method invokes a function. It sets the first parameter as the this of the function

For Example, the foo.call method invokes the foo method. The first argument bar becomes the this of the foo function

Apply

The apply() method invokes a function. It sets the first parameter as the this of the function

The apply method is very similar to the call method. They only differ in how they define the second parameter. The apply method excepts an array as the second parameter.

You can easily replace call in the previous example to apply.

Bind

The bind method allows us to change the this of a function and invoke it any time later. bind method does not invoke the function, but it returns a new function

For Example, the code s2=obj.show.bind(obj) sets the this of method show to obj and stores it in variable s2. Now we can invoke s2 anytime, it is always hardbound to obj.

Internally bind returns a wrapper function, which uses the apply method to bind the object to this.

Primitive Values & Explicit binding

If we pass a primitive value to call, apply or bind, they will convert it into its object representation. For Example, the string is converted to an object into using new String()

Passing null or undefined to bind, call & apply

The bind, call & apply functions ignores the null or undefined. instead, they will use the default binding.

Exceptions

There are Exceptions to the above rules of determining this.

Arrow functions

The arrow functions do not declare any this. Hence if we try to access this it will look for it in its parent scope.

You cannot even change the this of arrow function using apply, call or bind methods. i.e. because the arrow function does not have this

For Example, we use the arrow function for the getName method. It will return undefined because “this” for arrow function comes from its parent scope, which is the global scope.

Hence it is usually not recommended to use the arrow function as the method of an object.

For Example, you can refer to the This and arrow function

This in an ES6 Module

Inside an ES6 Module but outside the function this is always undefined. Also, ES6 Modules always runs on strict mode.

Hence the value of this inside a function invoked using function invocation is always undefined in an ES6 Module. However, the other types of function invocation like method, constructor invocation & explicit bindings work as mentioned above.

Precedence

It also important to know the Precedence of this binding. It is actually possible two bindings in a function call

  1. New binding or constructor calls
  2. Explicit Binding
  3. Method invocation or implicit binding
  4. Default binding

Here is some example of Precedence of this binding

Summary

Finally the summary of determining the this

  1. If we invoke the function with a new operator, this is always a new object.
  2. The function invoked with the call, apply & bind methods uses the first argument as their this. But if you pass null or undefined as the first argument, they use the default binding.
  3. The method invocations use the context object (i.e., object left of the dot notation)
  4. If all of the above fails, then use the default binding. It is null in the case of strict mode. Else global object (window in browser, global in NodeJs).

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top