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();
}