The first day on JS, if that. So, there is, for example, such code:

function Object1(a, b) { this.a = 0; this.b = 0; this.sum = function() { alert(a + b); } }; objs = []; for (var i = 0; i < 10; i++) { objs.push(new Object1(1, 1)); } setInterval(function() { for (var i in objs) { objs[i].b++; objs[i].sum(); } }, 200); 

The alert always displays 2, that is, in fact, the value of b does not change. How can it be changed in these conditions?

  • four
    alert(this.a + this.b); for a and b do not indicate anything in the function (method) - Alexey Shimansky
  • @ Alexey Shimansky yes, that is exactly ... Thank you very much! - JackDone

1 answer 1

Did you want this? Use only better console.log () ... nicer-more comfortable;)

 function Object1(a, b) { this.a = a; this.b = b; this.sum = function() { console.log(this.a + this.b); } }; objs = []; for (var i = 0; i < 10; i++) { objs.push(new Object1(1, 1)); } setInterval(function() { for (var i in objs) { objs[i].b++; objs[i].sum(); } }, 200);