Lets consider the following code:

function myfunc( aItems ) { 
   for ( var icount = 0; icount < aItems.length; icount++) {
      aItems[icount].newMethod = function() {
         return icount;
   return aItems;

const myObject = myfunc( [{one], {two}, {three}];
console.log( myObject[0].newMethod(); ); // 3
console.log( myObject[1].newMethod(); ); // 3
console.log( myObject[2].newMethod(); ); // 3

Variables that are declared with "var" always have function scope.
This means that these variables will always refer to the last value that has been assigned.
In this case we need to be explicit and tell the function to return the value of "icount" when it is assigned and not when you call the code.
Therefore the value of "icount" changes on each iteration of the loop.

The problem can be solved by making the following changes
This solution uses closures, higher order functions and self-invoking functions.

      aItems[icount].newMethod = ( function( icount ) { 
         return function() {
            return icount;
      } (icount) );

This problem can also be solved by just changing the "var" declaration to a "let" declaration.

   for ( let icount = 0; icount < aItems.length; icount++) { 

© 2020 Better Solutions Limited. All Rights Reserved. © 2020 Better Solutions Limited TopPrevNext