Parameter is the name of a variable instead of its value when initialising an object with a function as property

StackOverflow https://stackoverflow.com/questions/15618531

I'm trying to initialize properties of an object, one being a function. This works if I hardcode it:

subitems = {
   "1" : { "label": "Link1",
           "action": function(obj) {showURL(obj,"http://link1.com")}
   },
   "2" : { "label": "Link2",
           "action": function(obj) {showURL(obj,"http://link2.com")}
   }
}

or if I try doing it dynamically using a list in a variable

subitemdata = [['Link1','http://link1.com'],['Link2','http://link2.com']];

I use this to fill the label and action properties and generate the object

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

I get

subitems = {
     0 : { label: "Link1",
           action: (function(obj) {showURL(obj,subitemdata[i][1]);})
     },
     1 : { label: "Link2",
           action: (function(obj) {showURL(obj,subitemdata[i][1]);})
     }
}

How can I write the code so that in the 'action' property the strings 'subitemdata[i][1]' don't appear in the parameter list of the function 'showURL' but the actual values from the 'subitemdata' list 'http://link1.com' and 'http://link2.com' do?

I just can't manage to recreate the hardcoded object version when using the dynamic way to initialise the object.

有帮助吗?

解决方案

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]));

If you wrap it in an immediately invoked function and pass the value in, it should evaluate it immediately and the argument will be set to the value of the array contents instead of to the array reference itself.

Just to make sure you're clear though, as long as you don't modify subitemdata, the array reference will return the same thing when you work with it. You don't need to do this unless you want to hold onto the value of the array at that particular moment in time.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top