DEV Community

Cover image for What is THIS ?
Ram kumar Shrestha
Ram kumar Shrestha

Posted on

What is THIS ?

JavaScript the most popular programming language in the world. Almost every developer has been using JavaScript for various purposes from web app, mobile app, scripting to desktop app etc. JavaScript is so simple yet it can do almost everything.

One of the most confusing topic ever in JavaScript is this. this keyword sound so simple but I found many developers confused while using it.

Introduction

The this keyword refers to the context where a piece of code, such as a function's body, is supposed to run.

It severely depends on the runtime binding i.e, how its being invoked rather. Its value depends upon the context it appears.

Cases

  • Global

When this is used standalone i.e, directly on the code not inside any scope then usually it gives the global object (in non-strict mode) while its undefined in strict mode.

  • Class

If this is inside the class context then its value will be the class instance itself whether its on constructor or in any methods.

class ThisCalss{
   name = "ThisClass"
    constructor() {
      console.log(this.name) // "ThisClass" upon instace creation
   }

   printName() {
       console.log(this.name) // "ThisClass upon method invocation
   }
}

Enter fullscreen mode Exit fullscreen mode
  • Arrow Function

Arrow functions' this value depends on the enclosing lexical context's this.

const printName = () => {
     console.log(this.name);
};
Enter fullscreen mode Exit fullscreen mode

Result : As the printName is directly under global lexical scope the console will print undefined.

class ArrowExample {
  name = "ArrowExample";

  printName() {
    setTimeout(() => {
      console.log(this.name);  
    }, 100);
  }
 }

 const arrow = new ArrowExample();
 arrow.printName();
Enter fullscreen mode Exit fullscreen mode

Result: Here arrow function lexical scope is ArrowExample class so the output will be ArrowExample (value of name).

  • Conventional Function

In conventional functions (functions declared with the function keyword), this is determined by how the function is called, not where it's defined. The value of this depends on the calling context.

 function showThis() {
   console.log(this);
 }

 // Called directly
 showThis(); // window (in non-strict mode) or undefined (in strict mode)

 // As an object method
 const obj = {
    name: 'Object',
    show: showThis
 };
 obj.show(); // {name: 'Object', show: ƒ}

 // Using new keyword
 new showThis(); // showThis {}
Enter fullscreen mode Exit fullscreen mode
  • Object Inside object's method the this value is object itself.
 const laptop = {
     brand: 'Apple',
     getBrand: function() {
         return this.brand;
     }   
 }
console.log(laptop.getBrand()) // 'Apple'
Enter fullscreen mode Exit fullscreen mode

Passing this context

We can control the this context value with the help of bind, apply, call.

The bind, call directly invokes methods/functions with the this context value. The only difference between them is the second parameters. apply accepts comma separated value while call accepts the array in second parameter.

 function getThis() {
   return this;
 }   

 console.log(getThis.apply('this apply')) // 'this apply'

 console.log(getThis.call('this apply 2'))  // 'this apply 2'
Enter fullscreen mode Exit fullscreen mode

While bind will only create new reference of the function/method it will not be invoked. This bind is very helpful iff we have to pass the function as parameter to any other function/methods.

 function getThis() {
     return this;
 }   

 const newRef = getThis.bind('this bind');
 console.log(getThis()); // undefined
 console.log(newRef()); // this bind
Enter fullscreen mode Exit fullscreen mode

Conclusion

Understanding this in JavaScript requires careful attention to the context in which it's used. Here are the key points to remember:

  1. The value of this is determined by how a function is called (runtime binding)
  2. Class methods and object methods naturally bind this to their instance/object
  3. Arrow functions inherit this from their enclosing scope
  4. Conventional functions can have different this values based on their calling context
  5. bind, call, and apply provide ways to explicitly control this binding

Being mindful of these rules will help you avoid common pitfalls and use this effectively in your JavaScript code.

Top comments (0)