Reputation: 1374
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
where into a function I insert col and not the value of variable col!!!
How can I resolve my problem??
Upvotes: 0
Views: 519
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