gpt4 book ai didi

javascript - 如何将值设置为javascript对象元素中的函数?

转载 作者:行者123 更新时间:2023-12-03 12:08:21 24 4
gpt4 key购买 nike

我有这个代码:

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
};
};
}

如果我调试它,我会得到 enter image description here

在函数的哪个位置插入 col 而不是变量 col 的值!!!

如何解决我的问题?

最佳答案

当函数运行时,变量col不再包含创建函数时的值。您可以使用立即调用函数表达式 (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]);

}

关于javascript - 如何将值设置为javascript对象元素中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25078390/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com