0

why in this case "this" is a Window? I thought it would be Dog object, because it is on the left side of the dot.

 const Dog = {
        name: 'Spike',
        showThisDog: () => {
          console.log(this)
        }
    }

Dog.showThisDog()

I think I don't get how this keyword works. Can anyone explain it with this example? Thank U.

  • 1
    A fat arrow function doesn't create a function scope so the only scope here is the window. What is your expectation? There is no object scope in JavaScript. – Thomas Sablik Apr 23 '21 at 11:56
  • 1
    [Arrow function expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions): _"Does not have its own bindings to `this` or `super`, **and should not be used as methods.**"_ Why? -> [Arrow functions used as methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#arrow_functions_used_as_methods) – Andreas Apr 23 '21 at 11:56

1 Answers1

0

Your Dog object has no reference to this other than the Window. If you want to reference an internal property, try this.name.

In the global execution context (outside of any function), this refers to the global object.

Inside a function, the value of this depends on how the function is called. [...] because the value of this is not set by the call, this will default to the global object, which is window in a browser.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this#function_context

Matthew M.
  • 932
  • 10
  • 17