• 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 to this, this is the global window object... and in Espruino - where we do not have the global window - it refers to the global global, the equivalent of the browser's global window...

    With that, @Konkery, you can really beat it in even more than one way...

    • 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);.

    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!

  • @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);.

About

Avatar for allObjects @allObjects started