Yogesh Chauhan's Blog

Understanding the confusing and handy “This” keyword in JavaScript

in JavaScript on December 4, 2020

📌 The environment (or the scope) in which any JavaScript line is being executed is called “The Execution Context”.

The object that this variable refers to changes every time when the execution context is changed.

By default, the execution context is global which means that if a code is being executed as part of a simple function call then the this variable will refer to the global object.

📌 In the case of a browser, the global object is the window object.

In a Node.js environment, for example, a special object global will be the value of this.

Let’s take a look at the example below.


function foo () {
    console.log(this === window);
}
foo();

//true

This proves that this here refers to the global object, which is the window object in our case.

Note that, if strict mode is enabled for any function then the value of this will be undefined because in strict mode global object refers to undefined in place of the window object.

For example,


function foo () {
    'use strict';
    console.log(this === window);
}
foo();

//false

Let’s take a look at another example


function Person(first_name, last_name) {
    this.first_name = first_name;
    this.last_name = last_name;
    
    this.displayName = function() {
        console.log('Name:');
        console.log(`${this.first_name}`);
        console.log(`${this.last_name}`);        
    };
}

var john = new Person('John', 'Reid');
john.displayName();

//output
Name: 
John 
Reid

In the example above, when we call new on Person, JavaScript will create a new object inside the Person function and save it as this.

Then, the first_name, last_name and displayName properties will be added on the newly created this object.

Let’s take a look at the same example we saw earlier.


function simpleFunction () {
    console.log("Simple function call")
    console.log(this === window); 
}
simpleFunction();

//output
“Simple function call”
true

In the example above, the this keyword will refer to the global object, in our case, it’s the window object.

Let’s create a simple object.


let user = {
    count: 10,
    simpleFunction: simpleFunction,
    anotherFunction: function() {
        console.log(this === window);
    }
}

Now, we have a simpleFunction property referring to our simpleFunction function.

We have also added another property as a method called anotherFunction.

If we call user.simpleFunction(), we will get the following in our console’s output:


“Simple function call”

//false

It happens because simpleFunction() is now a property of the user object, then the this keyword will refer to the user object and not the global object in this case.

If we call user.anotherFunction() now, we should expect the same thing too.

Our this keyword will refer to the user object. So, console.log(this === window); should return false and we should get the following output in our console:


false

If just do the following, the output will be different.


let myFunction = user.anotherFunction;
myFunction();

//true

In the example above, we do a simple function call.

As we already know by now, if a method is invoked as a simple function, then the this keyword will refer to the global object which is in our case equals to the window object, and hence console.log(this === window); will print true.

Sources


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 How to add Read More Read Less Button using JavaScript? #3 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #4 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
What does useEffect do in React?ReactHow to use @each rule with key-value pair in SCSS?SCSSHow to modify navigation menus in WordPress?WordPressThe Drupal flowDrupalHow to avoid element shift on border change while hovering in CSS?CSSHow to add CurrencyPipe in TypeScript file in Angular 9 Project?Angular