-1

This question is related to topic here

I was expecting console to log window but it is logging LateBloomer. Please help me understand.

enter image description here

Triven
  • 351
  • 1
  • 4
  • 17
  • [Please don't post your code as an image.](//meta.stackoverflow.com/q/285551) – Suraj Rao Feb 09 '18 at 06:38
  • @SurajRao : Ok I will take care in future. – Triven Feb 09 '18 at 06:39
  • What do you mean by: "expecting console to log window"? – Arjun Panicker Feb 09 '18 at 06:41
  • You are writing a method on LateBloomer and hence using 'this' keyword you would be referring to that Object not the window object. Anyways what do you wanna log in window? – Jayanth Feb 09 '18 at 06:42
  • Duplicate of https://stackoverflow.com/questions/27643714/settimeout-calls-function-immediately-instead-of-after-delay – T.J. Crowder Feb 09 '18 at 06:54
  • In the mean time I get more down votes. Here is my understanding. https://stackoverflow.com/questions/38736902/settimeout-bind-and-this/48703271#48703271 . And I don't care about down votes :) – Triven Feb 09 '18 at 10:06

1 Answers1

1

Because

window.setTimeout(console.log(this), 1000);

calls console.log(this), and passes its return value (undefined) into setTimeout, exactly the way foo(bar()) calls bar and passes its return value into foo. So the this that gets logged is the current this where that line of code is.

Whereas in the linked question, they're doing this:

window.setTimeout(this.declare.bind(this), 1000);

which calls bind and passes its return value (a bound function) into setTimeout.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • too lazy to look for the dupe? ;) – epascarello Feb 09 '18 at 06:50
  • @epascarello: You know, I closed it as a dupe but of the wrong dupetarget, then...for some reason, didn't critically evaluate that it might be (well, must be) a dupe of a *different* dupetarget! Good point, thanks. – T.J. Crowder Feb 09 '18 at 06:53
  • @epascarello: Specifically: https://stackoverflow.com/questions/27643714/settimeout-calls-function-immediately-instead-of-after-delay if you'll do the honors? – T.J. Crowder Feb 09 '18 at 06:54
  • @epascarello: I've never been that happy with it. Do you have a better target? I'd love to switch to a better one. – T.J. Crowder Feb 09 '18 at 06:55
  • I guess I was not able to express my queries clearly so your answers didn't help much. I am developing my understanding and documenting it. I am sure I will get my head around it soon. I would like to share my notes . I will post my observations here if you find them in right direction and you think they relate to this question. https://www.dropbox.com/s/o9vqthx9jigccgb/thiskeyword.PNG?dl=0 – Triven Feb 09 '18 at 07:32