I’m new to closures and have a ‘gets me by doing most things’ understanding of javascript and so am wondering how I can improve etc on the following which was me trying to have an object that has a counter in it…trying to improve/further my understanding.
edit: the following code works, sure…but likely it is wrong (is it?)…I don’t have even close to an idea of whether it is code that is correct or incorrect…where can i improve…is there a better way to have a timer in an object/function?
function myObj() {
this.outputId = 'div_output1';
this.counter = 0;
this.limit = 10;
this.count = function() {
// reference to self
var me = this;
if (me.doStuff(me)) setTimeout(function() {
me.count();
},1000);
};
this.doStuff = function(me) {
if (me.counter >= me.limit) {
document.getElementById(me.outputId).innerText = 'count reached limit';
return false;
} else {
document.getElementById(me.outputId).innerText = 'count = ' + me.counter;
me.counter += 1;
return true;
}
}
}
// example usage of the object…
window.onload = function() {
var x = new myObj;
x.outputId = 'div_output2';
x.count();
var y = new myObj;
y.limit = 8;
y.count();
}
You are using closure correctly. Because when setTimeout calls your function, the ‘this’ will be ‘Window’ object and you have to create a closure (which you did by assigning ‘this’ to me) and accessing it.
Anyway, I would still write your code a little differently. I would make doStuff call itself instead of making it return true/false and then deciding whether to call doStuff again or not.
I don’t like how you are passing the ‘this’ object to this.doStuff function. There is no need for that. To understand how ‘this’ works in JavaScript, check my detailed answer on the subject.
Usage: