this question has answer here:
take @ code:
var arr = new array(); (var = 0; < 10; i++) { arr[i] = { func:function() { console.log(i); } } } arr[0].func(); i confused this, because thought work. each object in array print value given when function created.
right when call func(), prints 10 in console. there way make print 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 instead? thanks!
the problem function inside referencing variable 'i' increases every time. can store value of 'i' in each iteration in object alongside function this:
var arr = new array(); (var = 0; < 10; i++) { arr[i] = { func:function() { console.log(this.value); }, value: } } arr[0].func();
Comments
Post a Comment