You are reading a single comment by @Konkery and its replies.
Click here to read the full conversation.
-
@allObjects Does not work:
one is to define a local variable var _this = this; before the setInterval() and use it - _this in its function... (sometimes I just use var _ = this; to be short).
another one is to pass this as variable by passing it as 2nd+ parameter when setting up the interval: setInterval(function(_){ _.xyz(); },1000,this);.
EDIT: ...to cut to the chase:
Conclusion: Everything is just fine... @Gordon: 100 pts, @candidate: 0 - GAME OVER!
...TL;DR:... the rest of this and following posts....
hold your horses, @asez73...
@Konkery, I cannot speak for all details of JS in Espruino, but I get out of this challenge with the basic understanding and applying of
this
- the context object - which worked from the very beginning and is still working. JS has its quite own understanding of the context - the this - object... - and because JS is really really late binding,this
is evaluated when executed. Furthermore, the global functions have in the browser the global (variable)window
as the object... therefore, when a function is passed to a(window.)setInterval(f(){ console.log(this); },1000);
and the function refers tothis
,this
is the globalwindow
object... and in Espruino - where we do not have the globalwindow
- it refers to the globalglobal
, the equivalent of the browser's globalwindow
...With that, @Konkery, you can really beat it in even more than one way...
var _this = this;
before thesetInterval()
and use it -_this
in its function... (sometimes I just usevar _ = this;
to be short).this
as variable by passing it as 2nd+ parameter when setting up the interval:setInterval(function(_){ _.xyz(); },1000,this);
.Above uses just pure basic JS... yes, I know that
=>
has its fan base... see ES6 In Depth: Arrow functions article from MSDN's Jason Orendorff - but it has its caveats as well... for being unable to type function spelled incorrectly though is - for me - not one of them...In fairness, I cannot say wether node.js does it right... or browser or Espruino does it right, because - as said earlier - the caller of the function is not the object that does setup the interval - setInterval(... - it is the underlaying system... and I would not know where this would be specified... so I'm not surprised that that you and I get this error when coding it as in post #1.
Finally, @Konkery, I beg you for a favor and edit the conversation (title) to something like ```How do deal with this this in JS when I get error message "xyz not found!"
PS - Disclaimer: I could be wrong... would not be the first time... and also not the first time I have to blame myself... for a nice - stingy - laughter about myself!