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 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
Modules and its Core features in JavaScriptJavaScriptHow to create a function in SCSS (Sass)?SCSSHow to convert a number rounding to a specified number of decimals in JavaScript?JavaScriptHow to get category name using post id in WordPress?WordPressHow to modify navigation menus in WordPress?WordPressWhat happened to your Google Analytics Tracking ID, can’t find it?Miscellaneous