DEV Community

Aditya Singh
Aditya Singh

Posted on

JavaScript's 'this' Keyword: Understanding Its Power and Usage

💡 At first, it can be confusing, but once you grasp its concept and usage, you'll find it to be a powerful tool. In this blog, we'll demystify the this keyword, explaining what it is, how it works, and its different use cases.

What is 'this' in JavaScript?

In JavaScript, this is a special keyword that refers to the current execution context, or more precisely, the object that owns the code being executed. The value of this is determined dynamically at runtime, depending on how a function is called.

Global Context:

When this is used outside of any function or object, it refers to the global object. In browsers, the global object is the window object. For example:

console.log(this); // Points to the 'window' object in the browser
Enter fullscreen mode Exit fullscreen mode

Function Invocation:

When this is used inside a regular function (not an arrow function), its value depends on how the function is invoked:

  • Regular Function Call:

    When a function is called without any context (e.g., not attached to any object), this will also point to the global object (window in browsers) in non-strict mode. However, in strict mode, this will be undefined.

    function greet() {
      console.log(this); // 'this' points to 'window' or is 'undefined' in strict mode
    }
    
    greet();
    
  • Method Call:

    When a function is called as a method of an object, this refers to the object itself.

    const person = {
      name: 'John',
      greet: function() {
        console.log(this.name); // 'this' points to the 'person' object
      }
    };
    
    person.greet(); // Output: John
    
  • Arrow Functions:

    Unlike regular functions, arrow functions capture the this value lexically from their surrounding scope. This means that the value of this inside an arrow function is the same as the value of this outside the arrow function.

    const obj = {
      name: 'Alice',
      sayHello: function() {
        setTimeout(() => {
          console.log(this.name); // 'this' still refers to the 'obj' object
        }, 1000);
      }
    };
    
    obj.sayHello(); // Output: Alice
    
  • Constructor Functions:

    When using a constructor function with the new keyword, this inside the constructor refers to the newly created instance.

    function Person(name) {
      this.name = name;
    }
    
    const person1 = new Person('Bob');
    console.log(person1.name); // Output: Bob
    
  • Event Handlers:

    In event handlers, this usually points to the element that triggered the event.

    <button id="myButton">Click Me</button>
    
    <script>
    document.getElementById('myButton').addEventListener('click', function() {
      console.log(this); // Points to the button element
    });
    </script>
    

Conclusion

The this keyword in JavaScript plays a crucial role in determining the context in which a function is executed. Understanding its behavior is vital to writing effective and maintainable code. Remember, this can be different depending on the way a function is called, so pay close attention to the function invocation to correctly understand its value.

Top comments (2)

Collapse
 
wiseai profile image
Mahmoud Harmouch

Awesome tutorial! I just want to highlight an important ES6 feature you might find helpful. In modern JavaScript, you no longer need to explicitly type the word "function" when defining functions inside objects. It is also cross-browser compatible 1. So, your example can be simplified like this:

const person = {
  name: 'John',
  greet() {
    console.log(this.name); // 'this' points to the 'person' object
  }
};
person.greet(); // Output: John
Enter fullscreen mode Exit fullscreen mode

  1. You can learn more about this feature in the Mozilla Developer Network documentation: developer.mozilla.org/en-US/docs/W... 

Collapse
 
adii profile image
Aditya Singh

The ES6 feature you've mentioned is known as "method shorthand," and it indeed simplifies the process of defining functions inside objects. Thanks for sharing this valuable information!