function test() {
var interval;
this.a = 0;
interval = setInterval(function(){
a++;
this.a++;console.log(a,this.a);
},2000);
}
var b = {"a":0};
var a = 13;
setInterval(function () {
a++;
this.a++;console.log(a,this.a);
}, 2000);
So what's happening is that the setInterval is being run in the root scope (as 'this' isn't set for intervals iirc). That means that 'a' refers to a in the root scope, and 'this'==root, so this.a is exactly the same thing.
In Espruino a++ doesn't create an error if a doesn't exist, it just creates a locally in the function. Maybe that's not spec compliant and it could be changed in the future, but IMO soldiering on when there is no need to fail isn't very high priority.
There may be something strange with the handling of scopes for intervals I guess. If you can come up with a simple test that works in jsconsole/jsfiddle but that doesn't work in Espruino then I'll try and track it down though.
By the way, even if you delete the offending line a++, your code still doesn't work in something like jsconsole (it outputs NaN).
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.
When I run your code I get:
and if I type
dump()
I get:So what's happening is that the setInterval is being run in the root scope (as 'this' isn't set for intervals iirc). That means that 'a' refers to a in the root scope, and 'this'==root, so
this.a
is exactly the same thing.In Espruino
a++
doesn't create an error ifa
doesn't exist, it just createsa
locally in the function. Maybe that's not spec compliant and it could be changed in the future, but IMO soldiering on when there is no need to fail isn't very high priority.There may be something strange with the handling of scopes for intervals I guess. If you can come up with a simple test that works in jsconsole/jsfiddle but that doesn't work in Espruino then I'll try and track it down though.
By the way, even if you delete the offending line
a++
, your code still doesn't work in something like jsconsole (it outputsNaN
).