Glad you got this sorted - this is one of the classic JavaScript pitfalls. function() { ... } doesn't remember the value of this.
The easiest way to think of it (I find) is that JS is dumb, and when you use this, JS looks back at how the function was called (and not the function itself):
var a = {
b :42,
c : function() { print (this.b); }
};
a.c(); // prints 42
a["c"](); // prints 42
var z = a.c;
z(); // doesn't work
var somethingelse = {
b :"uh oh",
c : a.c
};
somethingelse.c(); // prints "uh oh"
However arrow functions do remember the value of this so in your case if you did:
Espruino is a JavaScript interpreter for low-power Microcontrollers. This site is both a support community for Espruino and a place to share what you are working on.
Glad you got this sorted - this is one of the classic JavaScript pitfalls.
function() { ... }
doesn't remember the value ofthis
.The easiest way to think of it (I find) is that JS is dumb, and when you use
this
, JS looks back at how the function was called (and not the function itself):However arrow functions do remember the value of
this
so in your case if you did:Then it'd work :/