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

160
Views
How does the "this" keyword works in these particular cases?

Suppose we have the following Javascript object:

const myObj2 = {
    name: "my object",
    thisOne: this,
    print1: function() {
        console.log("(1)", this.thisOne);
        console.log("(2)", this);
        
        const innerFuncDecl = function() {
            console.log("(3)", this);
        };
        
        const innerFuncArrow = () => {
            console.log("(4)", this);
        };

        innerFuncDecl();
        innerFuncArrow();

        (function(){
            console.log("(5)", this);
        })();

        (() => {
            console.log("(6)", this);
        })();
    },

    print2: () => {
        console.log("(7)", this);
    },

    print3: function(){
        console.log("(8)", this);
    },
};
    

If I call print1, print2 and print3 from my browser I have:

enter image description here

Questions:

  • Why (1) "this" points to "Window" and not to "myObj2"?
  • Why (2) and (8) "this" point to "myObj2", while (7) "this" points to "Window"?
  • Why (3) "this" points to "Window"? Is it because it's a function declaration, and function declarations are always hoisted to the global context? Same for (5)?
  • Why (4) "this" points to "myObj2"? Is it because it's a function expression, and function expression are never hoisted and maintain the context of the enclosing function? Same for (6)
about 4 years ago · Juan Pablo Isaza
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!