0

This code keeps the context in window:

const a = function () {
console.log(this);} //window

And this code changes the context to a2:

const a3 = {
    anyFunction: () => { console.log(this) } // window
}
a3.anyFunction(); 

Why this code keeps the context in window? how does the call stack works with anonymous functions that makes the context stay the same as if the function was not in the context of a4?

const a4 = {
    anyFunction: () => console.log(this) // window
}
a4.anyFunction();
Ric
  • 179
  • 1
  • 3
  • 16
  • 1
    What do you mean by context? Do you mean the `this` value? The call stack is not responsible for this – evolutionxbox Jan 30 '23 at 09:52
  • 2
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions _"Arrow functions don't have their own bindings to this, arguments, or super, and should not be used as methods."_ – Diego D Jan 30 '23 at 09:52
  • 1
    You seem to have messed up some parts in your question. You write `And this code changes the context to a2:` but in your example below you have `a3` where `this` refers to `window`. – t.niese Jan 30 '23 at 09:54
  • Although some people have used "context" for `this` over the years, "context" has a specific meaning in JavaScript which is unrelated to `this`. Just call it a `this` value. – T.J. Crowder Jan 30 '23 at 09:54
  • 1
    See [How does the "this" keyword work, and when should it be used?](/q/3127429/4642212), which explains all of this in detail. – Sebastian Simon Jan 30 '23 at 09:55
  • It has nothing to do with whether the function is anonymous (and it happens that none of the functions in your question is anonymous, they all have names even though they're all written using anonymous function expressions). It also has nothing to do with the call stack. It's just that arrow functions don't have a `this` binding, so they close over the value of `this` where they're created. – T.J. Crowder Jan 30 '23 at 09:56

0 Answers0