0

const obj = {
  a: "prakash",
  name: function() {
    console.log(this.a);
  }
}

// Returns undefined because we extract
// it from obj and this is points to window object.
setTimeout(obj.name, 500);

// returns Prakash
setTimeout(function() {
  obj.name();
}, 500);

Could you please explain me how it is working inside the anonymous function. I know I can use "bind", instead of anonymous function. But I wanna know, the reason why it works when you use anonymous function.

Andy
  • 61,948
  • 13
  • 68
  • 95
  • `setTimeout(obj.name(), 500);` works – GrafiCode May 26 '22 at 16:47
  • 1
    @GrafiCode that will print the name immediately, not after a delay – Michael Horn May 26 '22 at 16:48
  • Because all it matters is how you call it: `a.b()` will always (try to) set `a` as `this`. The reason it doesn't work when you pass it to `setTimeout` (or really, any other function), because the function will receive it into a parameter (like `x`) and context info is lost (it calls it like `x()`; without `a.`) – FZs May 26 '22 at 16:50
  • @prakash pappu In addition to the answer linked above, this link has an in-depth explanation of this precise issue: https://gist.github.com/zcaceres/2a4ac91f9f42ec0ef9cd0d18e4e71262 - See the section "Callbacks and this" – Michael Horn May 26 '22 at 16:52
  • oh right, «There's also no option to pass a thisArg to setTimeout as there is in Array methods such as forEach() and reduce().» «Solutions: USE A WRAPPER FUNCTION, USE BIND()» https://developer.mozilla.org/en-US/docs/Web/API/setTimeout – GrafiCode May 26 '22 at 16:53

0 Answers0