YogeshChauhan . com

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

amazon

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 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

How to add Date and Time picker in HTML and get the values using JavaScript?HTMLHow to add menu to your WordPress theme?WordPressCrypto.getRandomValues() method in JavaScriptJavaScriptHow to remove border from :visited image, link or button?CSSWhy does MOV matter in IT or any kind of projects?MiscNATURAL JOIN in PostgresPostgres