"this" keyword in javascript

"this" keyword in javascript

ยท

2 min read

Many student has different thought about "this" keyword, just like ''this'' keyword is only available in Regular Function but not in Arrow Function .

But if you ask them to , what is the reason of this statement they don't know, so today i will disscuss about this keyword and its myth ๐Ÿ˜ƒ.

we solve this confusion in 3 examples

  1. i just make an file dummy.js
function coderfussion() {
    console.log("regular function", this)
}

const myArrowFun=()=>{
    console.log("arrow function", this)
}

coderfussion()
myArrowFun()

i run this code in Browser enviroment and result is

Now we run same code in Node enviroment

Hmm , intresting thing means same code in different enviroment give different result.


  1. Now we can see howo this both function behave in an object

     const myObject = {
            name: "gokuthecoder",
            rollno: 1,
            getDetails1: function(){ console.log( "getDetails1", this) },
            getDetails2: ()=>{ console.log( "getDetails2" ,this) }
     }
    
     myObject.getDetails1()
     myObject.getDetails2()
    

    Hmm , when run then getDetails1 'this' is refers current Object , but getDetails2 give undefined , then what is refers getDetails2. we need to see an example to understand arrow function.

  2.  const myArrowFunction = () => {
         this.class = "LKG";
    
         const myObject = {
             name: "gokuthecoder",
             rollno: 1,
             getDetails1: function () { console.log("getDetails1", this) },
             getDetails2: () => console.log("getDetails2", this.class)
         }
    
         myObject.getDetails2()
     }
    
     myArrowFunction()
    

    we can see that in arrow function inherit this from parent scope
    , while a regular function this refers to the current object .

or

Arrow functions in JavaScript do not have their own this context. Instead, they inherit this from the parent scope at the time they are created. This is a key feature of arrow functions and is what makes them different from regular functions.

I hope guys , this post is helpful for you . Happy Coding

ย