View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
  1. Home
image

JavaScript Tutorial Concepts - From Beginner to Pro

Learn JavaScript from scratch! Our tutorial covers basics to advanced concepts. Start learning today!

  • 24
  • 9 Hours
right-top-arrow
17

JavaScript This Keyword

Updated on 08/08/2024342 Views

The word this might seem simple at first, but according to me, it is a surprisingly nuanced part of JavaScript. I believe that mastering JavaScript this keyword is essential for writing clean, predictable JavaScript code. 

The ‘this’ keyword within a JavaScript function refers to the current execution context. This context can change depending on how the function is called.

Let's dive into how this works, its common pitfalls, and how to use this effectively. We will also explore various scenarios in this tutorial and understand the different applications of JavaScript this keyword.

What is JavaScript this keyword?

In essence, this refers to the object that a function is currently being executed within. The value of this is determined not by where the function is defined, but by how it's called. This dynamic nature can be both powerful and confusing if not fully understood.

Common Scenarios for JavaScript this keyword

Here are some common scenarios where JavaScript this keyword is used:

  • Inside an object's method: When a function is a property of an object, this inside that function usually refers to the object itself.
  • In regular functions: Inside a standalone function (not within an object), this often refers to the global object (window in browsers). This can lead to surprises if you're expecting it to behave like it does within object methods.
  • Constructor functions: When a function is used as a constructor (with the new keyword), this refers to the newly created object being constructed.
  • Event handlers: Within event handlers, this often refers to the DOM element that triggered the event.

Controlling JavaScript this Keyword

Let's delve into the various techniques you can use to control the value of 'this' in JavaScript for precise and predictable code behavior:

1. call() and apply()

The call() and apply() methods allow you to explicitly set the value of ‘this’ when calling a function. apply() takes an array of arguments, while call() accepts arguments individually.

Syntax:

function.call(thisValue, arg1, arg2, ...);

function.apply(thisValue, [arg1, arg2, ...]);

Example:

Code:

const person = { name: "Maya" };

const robot = { name: "R2D2" };

function sayHello(message) {

    console.log(`${this.name} says: ${message}`);

}

sayHello.call(person, "Greetings!");   // Output: Maya says: Greetings!

sayHello.apply(robot, ["Beep boop"]);  // Output: R2D2 says: Beep boop

Note: JavaScript const is a JavaScript keyword for declaring constants

2. bind()

bind() creates a new function with this permanently bound to a specific value. This method returns a new function, rather than immediately executing the original function.

Syntax:

const newFunction = originalFunction.bind(thisValue); 

newFunction(); 

Example:

Code

const pet = { name: "Fluffy"};

 function petIntro() {

      console.log(`My name is ${this.name}`);

 }

 const boundIntro = petIntro.bind(pet);

 boundIntro(); // Output: My name is Fluffy 

3. Arrow Functions

Inherit this from the enclosing lexical scope. Arrow functions provide a more predictable and concise way to manage this.

Syntax:

const myObject = {

    counter: 0,

    logger: () => {

        console.log(this.counter);  // 'this' refers to myObject

    }

};

Example:

Code:

const myObject = {

    counter: 0,

    logger: () => {

        console.log(this.counter);  // 'this' refers to myObject

    }

};


4. Strategic Use of JavaScript this keyword (Combination Strategies)

Often, the best approach for controlling this includes a combination of these techniques. Consider the following scenario within a class:

Example:

Code:

class Timer {

    constructor() {

        this.interval = 1000;

    }

    start() {

        // Ensure the correct `this` in the callback

        setInterval(() => { 

            this.tick();  

        }, this.interval); 

    }

    tick() {

        console.log("Time elapsed!");

    }

}

In-Depth Exploration of JavaScript this Keyword

Inside an Object's Method

Code:

const person = {

    name: "Bob",

    greet: function() {

        console.log("Hello from " + this.name);

    }

};

person.greet(); // Output: Hello from Bob

Here, person.greet() is called. Since greet is a method defined within the person object, this inside greet refers to person itself.  This allows you to access the object's properties (like name) within the method.

Regular Function (Global Scope)

Code:

function announce() {

    console.log(this); // Might print the window object in a browser

}

announce(); 

When you call announce() without being part of an object, this often defaults to the global object, which is window in a browser environment. This can lead to unexpected behavior if you intend this to reference a specific object. Learning JavaScript with keywords is essential to avoid these types of unexpected instances.

Constructor Functions

Code:

function Car(model, year) {

    this.model = model;

    this.year = year;

    this.getInfo = function() {

        console.log("This car is a " + this.model + " from " + this.year);

    };

}

const myCar = new Car("Tesla Model S", 2024);

myCar.getInfo();  // Output: This car is a Tesla Model S from 2024

When you use new with a function like Car, this inside the function refers to the newly created object (myCar in this case). This allows you to assign properties (like model and year) and methods (like getInfo) to the new object instance.

Note: JS new keyword is a JavaScript keyword for declaring constants

Event Handlers

Within event listeners (addEventListener), this refers to the DOM element that triggered the event.

Example HTML:

<button id="myButton">Click Me</button>

Example JS::

const button = document.getElementById("myButton");

button.addEventListener("click", function() {

    console.log(this); // Output: refers to the button element

});

In this case, clicking the button makes this point to the <button> element itself.

JavaScript this Keyword within Classes

Code:

class Car {

    constructor(brand, model, year) {

        this.brand = brand; 

        this.model = model;

        this.year = year; 

    }

    getDetails() {

        console.log(`This is a ${this.brand} ${this.model} from ${this.year}`);

    }

}

const myCar = new Car("Ford", "Mustang", 2022);

myCar.getDetails(); // Output: This is a Ford Mustang from 2022

The constructor function is called when you create an object using new. this within the constructor refers to the newly created object, allowing you to set its properties. Inside methods like getDetails(), this refers to the specific object instance (myCar in this case).

Advanced Techniques for Managing JavaScript this Keyword

Here are some advanced techniques for managing JavaScript this keyword:

  • Using that or self: A common older practice was to assign this to a variable like that or self at the beginning of a function to preserve the reference.
  • Prototypal Inheritance: Understanding JavaScript's prototypal inheritance model is crucial for comprehending how this works in complex object hierarchies.

Common Pitfall: Losing this in Callbacks

Problem:

Solution A: {Replacing the existing setTimeout() function}

    setTimeout(() => { // Arrow function inherits 'this'

        this.seconds++;

        console.log(this.seconds); 

     }, 1000);

Fixed code:

Code:

class Timer {

   constructor() {

       this.seconds = 0;

   }

   start() {

              setTimeout(() => { // Arrow function inherits 'this'

        this.seconds++;

        console.log(this.seconds); 

     }, 1000);

   }

}

const timer = new Timer();

timer.start(); 

Solution B: {Replacing the existing setTimeout() function}

    setTimeout(function() {

        this.seconds++;

        console.log(this.seconds); 

    }.bind(this), 1000); 

Fixed code:

Code:

class Timer {

   constructor() {

       this.seconds = 0;

   }

   start() {

             setTimeout(function() {

        this.seconds++;

        console.log(this.seconds); 

    }.bind(this), 1000); 

   }

}

const timer = new Timer();

timer.start(); 

If you wish to learn web development and tools such as JS, you can check out upGrad’s full stack development courses.

Code Challenges with JavaScript this keyword

Challenge 1: Object Method Madness

Code:

const person = {

    firstName: "Alice",

    lastName: "Smith",

    fullName: function() {

        // How can we access firstName and lastName within this function

        // to return the full name?

        console.log(this.firstName + " " + this.lastName);

    }

};

person.fullName(); // Output: Alice Smith

Inside fullName, this refers to the person object, allowing you to access its properties (firstName and lastName) using dot notation.

Challenge 2: this in a Nested Function

Code:

const myObject = {

    value: 10,

    getValue: function() {

        function innerFunction() {

            console.log(this.value); // What will this print?

        }

        innerFunction();

    }

};

myObject.getValue(); 

This is a tricky one because innerFunction is defined within getValue, it doesn't inherit this from myObject. Here, this inside innerFunction would likely refer to the global object (window). To fix this, you can use techniques like bind() or arrow functions to ensure innerFunction uses the correct this value.

Practical Applications of JavaScript this keyword

The this keyword is fundamental for building real-world JavaScript applications. Here are some applications of this:

  • User interfaces: this in event handlers lets you dynamically respond to user actions on specific elements of a web page.
  • Object-oriented programming (OOP): Encapsulate behavior with objects. Access and modify an object's state using this within methods (like in the person object examples).
  • AJAX requests: When working with asynchronous requests, managing this is crucial, especially in callback functions, to ensure you have access to the correct context.

Wrapping up

The this keyword in JavaScript serves as a vital reference to the current execution context. Understanding how its value is determined within different scenarios is fundamental to writing well-structured object-oriented JavaScript code. While the default behavior of JavaScript this keyword can sometimes be surprising, techniques like call(), apply(), bind(), and arrow functions provide the necessary tools to gain precise control. 

If you wish to learn JavaScript and other essential tools you will need as a developer, you can enroll in upGrad’s software engineering courses.

Frequently Asked Questions

1. Why use this keyword in JavaScript?
The this keyword is used in JavaScript to access and manipulate properties and methods within an object's context or the current execution context. This is essential for object-oriented programming and working with dynamic data.

2. Why this keyword is not mostly used in JavaScript?
The this keyword is widely used in JavaScript, especially in OOP and event handling. However, the dynamic nature of JavaScript this keyword can lead to confusion if not understood properly.

3. How to bind the this keyword in JavaScript?
You can bind JavaScript this keyword using the following methods:

  • bind(): Creates a new function with a permanently bound this value.
  • call(): Explicitly sets this when calling a function.
  • apply(): Similar to call() but takes arguments as an array.

4. How to avoid this keyword in JavaScript?
You can sometimes avoid using JavaScript this keyword by:

  • Using arrow functions, which inherit this from their enclosing scope.
  • Employing destructuring and modular patterns for organizing your code.

5. What is the scope of this in JavaScript?
The scope of JavaScript this keyword is determined by how a function is called, not where it's defined. Its value can change depending on the context.

6. Can we use this in arrow function?
Yes, but arrow functions behave differently than regular functions regarding this. Arrow functions inherit this from their enclosing (lexical) scope, providing more predictable behavior and often reducing the need to explicitly bind this.

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. .