Apologies for the title, but there's no succinct way of putting it. I'm working on the following code, which aims to chain a set of counters together, into one big one. To build a clock or whatever.
function subcounter(max, name, trigger) {
this.index = 0;
this.trigger = trigger;
this.name = name;
this.tick = function() {
this.index++;
if (this.index==max) {
this.index=0;
this.trigger();
}
}
this.show = function() {
alert(this.name+' triggered');
}
}
y = new subcounter(2,'y',function(){alert('finished')});
x = new subcounter(2,'x',y.tick);
for (var index = 0; index < 12; index++) {
alert ([x.index, y.index]);
x.tick();
}
This doesn't work as expected. For debugging I replaced the line above with:
x = new subcounter(2,'x',y.show);
And found that 'x triggered' is shown instead of 'y triggered', which I would expect. What's going on here? (Tried in Firefox).
Thanks for your answers or pointing me to documentation on this. However, my brain still fails to understand how a function scoped to one object instance: 'y.show' can ever resolve to that function on a different object instance.
The answer seems to be:
x = new subcounter(2,'x',function() {y.tick();});
But I'd still like to really understand why the original doesn't work as expected.
this: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…