Watching video tutorial on switch functions. And there the author gave an example:

let person = { name: "Bob", greet: function() { setTimeout(() => { console.log('Hello, my name is ' + this.name); console.log('this is', this); }, 2000); } }; 

But, as a person working with javascript for some time, I know that this in the body of setTimeout refers to setTimeout and in this example this problem is solved using the arrow function, but why then this in this case refers to the person object, and not on greet: function() ? And how is it most effective to remember when and what this refers to?

1 answer 1

  1. In timers, the function refers not to setTimeout (what does this even mean?), But to window .
  2. When a function is called as a method (via a dot, for example), this inside is set to the parent object. And the arrow, accordingly, inherits him.
  3. It is simple to memorize: as a function - window (strictly speaking - undefined ), as a method - onto a parent object. And then just watch what came from and where.
    However, there are many pitfalls: from Function#bind and Function#apply/call to arrows.