padibro
padibro

Reputation: 1374

How set value into a function in the element of javascript Object?

I have this code:

this.mGroupFunctions={};
        for(var i=0; i<cols.length; i++){
            var col=cols[i];
            this.mGroupFunctions[col]=function(oContext) {
                var name = oContext.getProperty(col);
                return {
                  key: name,
                  text: name
                };
              };
        }

If I debug it i obtain enter image description here

where into a function I insert col and not the value of variable col!!!

How can I resolve my problem??

Upvotes: 0

Views: 519

Answers (1)

Guffa
Guffa

Reputation: 700670

When the function runs, the variable col no longer contains the value that it had when the function was created. You can use an immediately invoked function expression (IIFE) to create a closure that captures the value of col for each iteration in the loop:

this.mGroupFunctions = {};
for(var i=0; i<cols.length; i++){      

  this.mGroupFunctions[cols[i]] = (function(col){

    return function(oContext) {
      var name = oContext.getProperty(col);
      return {
        key: name,
        text: name
      };
    };

  })(cols[i]);

}

Upvotes: 1

Related Questions