What do I want to achieve?
I have an class called Looper. I want to give each object a name and an own looper.
Results I expect
Created Looper Object... one Created Looper Object... two one - 1 two - 1 one - 2 two - 2 one - 3 two - 3 one - 4 two - 4 one - 5 two - 5 ....... My code
With this code I expect it to work..
var Looper = (function (window, document, $) { this.i = 1; var Looper = function () { console.log('Created Looper Object...'); } var getName = function () { return this.name; } var setName = function (newName) { this.name = newName; } var loop = function () { console.log(getName() + ' - ' + this.i); this.i = this.i + 1; } var startLoop = function () { window.setInterval(loop, 1000); } Looper.prototype = { getName: getName, setName: setName, start: startLoop } return Looper; })(window, document, jQuery); var one = new Looper(); one.setName('one'); console.log(one.getName()); one.start(); var two = new Looper(); two.setName('two'); console.log(two.getName()); two.start(); jsFiddle example
My results
But it doesn't....
Created Looper Object... one Created Looper Object... two result - 1 result - 2 result - 3 result - 4 result - 5 ....... Can someone tell me why it doesn't?
My problem is that is can set this.name for each object.
But I cannot set this.i for each object. They overtake each others i. Looks like this.i is static?!?!?
Also when I use console.log(two.getName()); it works. But within the loop this.name is result?
oneortwo?resultand they increment each othersi...window.name.thisrefers to thewindowobject, and it happens thatwindow.namein jsfiddle isresult.