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

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

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

I would call the javascript function "addNew". I have tried.

 json.callback(json); 

But does not work. Any idea?

+4
source share
3 answers

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

 window[json.callback](json); 

If your code is well structured, you will likely have an object containing all the functions that JSON can 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); 
+12
source

Do not use eval, use

 window[json.callback](json); 

If the function is in the global scope. Instead, use an area instead of a window.

+9
source

Use eval(json.callback+'()');

-2
source

Source: https://habr.com/ru/post/1285735/


All Articles