简体   繁体   English

如何调用一个在Json对象中传递其名称的函数?

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

I have a JSON object with a key element called callback. 我有一个JSON对象,其中包含一个名为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. 我想调用javascript“addNew”函数。 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. 如果您的代码结构良好,您可能会有一个包含JSON可以调用的所有函数的对象。

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 不要使用eval,请使用

window[json.callback](json); 

If the function is in the global scope. 如果函数在全局范围内。 Use the scope instead of window otherwise. 否则使用范围而不是窗口。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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