I have an object and i put it in a Array, and the i iterate the array with for
and for each object in the array i put a set interval for calling a method of the object with a parameter, but i cant.
This is my "Class".
function ClassTest() {
this.test = function(word) {
console.log(word);
}
}
The i create the object and put it on a Array:
var array = [];
var objectTest = new ClassTest();
array.push(objectTest);
And when i set the Intervals:
for(var i = 0; i < array.length; i++) {
array[i].loop = setInterval(function() {
array[i].test("hello")
}, 1000);
}
The problem is that the var i
in the setInterval function dosent exist, i can create a var index
and the it exist but i dont understand why index
exist and the var i
not.:
for(var i = 0; i < array.length; i++) {
var index = i;
array[i].loop = setInterval(function() {
array[index].test("hello")
}, 1000);
}
I get this error when i dont use the index
var:
Uncaught TypeError: Cannot read property 'test' of undefined