How set value into a function in the element of javascript Object?
-
02-01-2020 - |
Question
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??
Solution
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]);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow