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??
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]);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.