Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
ambiguous behaviour of this keyword in javascript

first version of code :

const myobj = {
    a1 : 10,
    b1 : 20,
    c1 : 30,

    myfunc1 :function() {

    console.log(this)
    
    const myfunc2  =  function ()     {
        let a2 =100
        console.log(this)
    }
        myfunc2()

    }

}



myobj.myfunc1()

output :

{a1: 10, b1: 20, c1: 30, myfunc1: ƒ}
Window {window: Window, self: Window, document: document, name: '', location: Location, …}

second version of code :

const myobj = {
    a1 : 10,
    b1 : 20,
    c1 : 30,

    myfunc1 :function() {

    console.log(this)
    
    const myfunc2  =   () =>     {
       let a2 =100
        console.log(this)
    }
        myfunc2()

    }

}



myobj.myfunc1()

output :

Object a1: 10 b1: 20 c1: 30 myfunc1: ƒ ()[[Prototype]]: Object
Object a1: 10 b1: 20 c1: 30 myfunc1: ƒ ()[[Prototype]]: Object

I am having trouble understanding the this keyword behaviour in javascript

my problem : In my first version of code when I call this keyword inside myfunc1 then it is referencing myobj but inside the same function when I create another function as myfunc2 and call it inside the function then it is referencing the window object why it is behaving like this even though the function is called and created inside the myobj object literal

In my second version of code when I call this keyword inside myfunc1 then it is referencing myobj and inside the same function when I create another function as myfunc2 and call it inside the function myfunc1 the it is referencing the myobj object literal as the arrow function takes the scope in which it has been created

my problem is why in first version of code even though the function is created and called inside the myobj literal it is referencing the window object

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

“This” keyword refers to an object that is executing the current piece of code. It references the object that is executing the current function. If the function being referenced is a regular function, “this” references the global object. If the function that is being referenced is a method in an object, “this” references the object itself.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!