0

I am trying to understand this piece of code and having hard time with it -

const obj = {
  name: "Cristiano",
  lname: "Ronaldo",
  getName: function () {
    function another() {
      console.log(this);
    }
    another();
  },
};

obj.getName();

The console logs to the Window object which is quite confusing.

Any ideas as to why?

Secondly, this is the way I am interpreting such questions -

In case of function declarations (statements), the this object refers to the - just immediate parent object. If it's a function then the this binding to the same function and so on.
In case of ES6 arrow functions, the this object refers to the - The this binding of parent normal function declaration.

That's the reason why -

const obj = {
  name: "Cristiano",
  lname: "Ronaldo",
  moreObj: {
    name: "Siiii",
    getName: function () {
      const named = () => this.name;
      console.log(named());
    },
  },
};

obj.moreObj.getName();

returns Siiii as log.

Am I understanding it right?

Thanks in advance :)

Aryan Shridhar
  • 176
  • 3
  • 7
  • 1
    `another()` calls the `another` function without doing anything to set what `this` should be during the call, so in loose mode code (the default), `this` will be set to the global object (`window` on browsers) during the call. All the rest of the code shown is irrelevant, it's that one thing (`another()`) that determines what `this` is in the above. Where the function is defined is completely irrelevant to `this` with traditional functions (ones using the `function` keyword). – T.J. Crowder Oct 25 '22 at 15:43
  • 1
    See also [arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions), which handle `this` differently from traditional functions and methods: They don't care what `this` they're called with; instead, they *close over* the `this` where they're defined. – T.J. Crowder Oct 25 '22 at 15:44
  • 1
    Oof yeah! If I modify it to another.call(this), it works as expected! Been a long day I suppose! Thanks :) – Aryan Shridhar Oct 25 '22 at 16:19

0 Answers0