0

I'm having difficulty about 'this' keyword determination.

At creation phase of Execution context, 'this' variable gets created.

And 'this' will be determined by which environmnent its called. it doens't matter how its declared, its determined by how its called right? according to following link, https://javascript.info/object-methods

In JavaScript this is “free”, its value is evaluated at call-time and does not depend on where the method was declared, but rather on what object is “before the dot”.

then can anybody explain following code?

function hey(){
   const x = 3;
   console.log(this)
}

hey() /// result :: window

I think it should log { x: 3}.

when console.log runs, execution stack will look like this :: [global execution context , hey context]

and since function 'hey' is also object, 'this' should point hey context's variable environment.

but results global environment.

I really don't get this phenomenon.... any ideas about this??

searched for articles, googled, etc..

  • 1
    You obviously didn't google enough, but here is a good article https://dmitripavlutin.com/gentle-explanation-of-this-in-javascript/ – IP002 May 24 '23 at 07:33
  • 1
    You're mixing `this` with *scope* if you expect the result to be `{ x: 3}` which lists all bindings in scope of the function. These are two entirely different things. Here is a quick reason why that is: functions in JS are a light-weight way to get free methods. You can have `function getAge() { return this.age; }` and it would work if executed against a `Person` object or a `Document` object as long as they both have an `age` property. The `this` would just point to the object against it's executed. If called as a function, it's `undefined` (or `window` in sloppy mode). – VLAZ May 24 '23 at 07:43

0 Answers0