14. this keyword - Javascript

this is a special keyword in JavaScript that refers to the object that is executing the current function. Its value depends on how the function is called.

  1. this Used Alone (Global Context)

     //In Node.js
     console.log(this); // {} (return empty object)
    
     //In Browser
     console.log(this); // Window object (return window object)
    

2.this in a Regular Function

//In Node js
function showThis(){
    console.log(this);  // global object (In Strict Mode it is undefined)
}
showThis() 

//In Browser
function showThis(){
    console.log(this);  // window object (In Strict Mode it is undefined)
}
showThis()
  1. this inside object

     // In Node js
     let obj ={
         name:"Ayy",
         age:"21",
         f: function(){
             console.log(this)
         }
     }
     obj.f();  //{ name: 'Ayy', age: '21', f: [Function: f] } (return object itself)
    
     //In Borwser -> return object itself
    
  2. this in an Event Handler

    In an event listener, this refers to the element that triggered the event.

     <button id="btn">Click Me</button>
     <script>
     document.getElementById("btn").addEventListener("click", function() {
         console.log(this); // Output: <button id="btn">Click Me</button>
     });
     </script>
    
  3. this in an Arrow Function

    • Arrow functions do not have their own this.

    • They inherit this from their surrounding lexical scope

    •     const obj = {
              name: "Arrow Function",
              getName: () => {
                  console.log(this.name);
              }
          };
          obj.getName(); // Output: undefined
      

Inside a method

    const obj = {
        name: "JavaScript",
        getName: function () {  // arrow inside function
            const arrowFn = () => console.log(this.name);
            arrowFn();
        }
    };
    obj.getName(); // Output: "JavaScript"

Interview questions

  1. What will be the output of this function inside an object?

     const obj = {
         name: "JavaScript",
         getName: function () {
             console.log(this.name);
         }
     };
     obj.getName();
    
    • Output: "JavaScript"

    • this refers to obj because getName() is called as an object method.

  2. How do you fix this inside a nested function?

    • Arrow functions (they inherit this from their parent scope).

    • bind(this) to manually set this.

        const obj = {
            name: "JavaScript",
            getName: function () {
                const innerFunction = () => console.log(this.name);
                innerFunction();
            }
        };
        obj.getName(); // Output: "JavaScript"
      

Next Topic :

15. call , apply , bind