[英]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 如果我调试它,我得到
where into a function I insert col and not the value of variable col!!! 我在函数中插入col而不是变量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. 当函数运行时,变量
col
不再包含创建函数时的值。 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: 您可以使用立即调用的函数表达式(IIFE)创建一个闭包,该闭包捕获循环中每次迭代的
col
值:
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]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.