我正在尝试初始化一个对象的属性,其中一个是函数。 如果我对其进行硬编码,这将有效:
subitems = {
"1" : { "label": "Link1",
"action": function(obj) {showURL(obj,"http://link1.com")}
},
"2" : { "label": "Link2",
"action": function(obj) {showURL(obj,"http://link2.com")}
}
}
或者如果我尝试使用变量中的列表动态地执行此操作
subitemdata = [['Link1','http://link1.com'],['Link2','http://link2.com']];
我用它来填充标签和操作属性并生成对象
subitems = {};
for (i=0; i<subitemdata.length;i++) {
subitems[i] = {};
subitems[i].label = subitemdata[i][0];
subitems[i].action = function(obj) {showURL(obj,subitemdata[i][1])};
}
我明白了
subitems = {
0 : { label: "Link1",
action: (function(obj) {showURL(obj,subitemdata[i][1]);})
},
1 : { label: "Link2",
action: (function(obj) {showURL(obj,subitemdata[i][1]);})
}
}
如何编写代码,以便在“action”属性中,字符串“subitemdata[i][1]”不会出现在函数“showURL”的参数列表中,而是出现在“subitemdata”的实际值中'列表'http://link1.com '和'http://link2.com ' 做?
当使用动态方式初始化对象时,我无法重新创建硬编码对象版本。
最佳答案
subitem[i].action = (function makeConstantStr(str){
//this takes the array, gets the value and returns a new function with
//the current value in the array as the 2nd argument of the innermost function
return function(obj) {showURL(obj,str)};
}(subitemdata[i][1]));
如果将它包装在立即调用的函数中并传入值,它应该立即对其求值,并且参数将设置为数组内容的值,而不是数组引用本身。
只是为了确保您清楚,只要您不修改 subitemdata,数组引用在您使用它时就会返回相同的内容。除非您想保留该特定时刻的数组值,否则您不需要执行此操作。
关于javascript - 当使用函数作为属性初始化对象时,参数是变量的名称而不是其值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15618531/