简体   繁体   中英

How to invoke a function, whose name is passed in Json object?

I have a JSON object with a key element called callback.

{
"id":34,
"description":"",
"item_id":4,
"callback":"addNew",
"filename":"0000072.doc",
"type":"News",
"ext":"doc",
"size":46592
}

I would like to call the javascript "addNew" function. I tried.

json.callback(json);

But does not work. Any idea?

Assuming it is a global function (it shouldn't be):

window[json.callback](json);

If your code is well structured you will probably have an object containing all the functions the JSON could call.

var myObject = {
  func1: function myObject_func1_method(foo) {
    return 1;
  },
  func2: function myObject_func2_method(foo) {
    return 2;
  }
}

Then you can:

myObject[json.callback](json);

Don't use eval, use

window[json.callback](json); 

If the function is in the global scope. Use the scope instead of window otherwise.

使用eval(json.callback+'()');

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM