How to pass parameters to eval as an object?

I have this json, and when I get this json, I need to run a function that comes in the callback object.

{
    formId: 'snn_service_item_form',
    item_id: '1',
    item_title: 'some item',
    item_description: '',
    item_duration: '10',
    item_price: '120',
    item_level_1 : 1,
    item_level_2 : 0,
    item_level_3 : 1,
    item_type: 'p',
    callback : {
        callbackName : 'getServices',
        callbackParams : {
            _param1 : 1,
            _param2 : 2 
    } 
} 
}

so according to this i need to run this:

getServices(1,2);

I can do this using the eval function, for example:

eval(json.callback.callbackName+'(\''+ json.callback.callbackNParams._param1 +'\',\''+ json.callback.callbackNParams._param2 +'\')');

I can automate this by putting it in in and for inputting parameters to a string, but I don't think this is the best way to go.

there is a way to assign a function name from var and specify its parameters as an object, in my case it seems to be:

json.callback.callbackName(json.callback.callbackParams);

I know that this is not a way to do this, but that is what I want to know.

Thanks, Sinan.

+5
source share
2 answers

, ( ).

, eval ( , ), window:

var args = [];
for(var p in json.callback.callbackParams) {
    args.push(json.callback.callbackParams[p]);
}
window[json.callback.callbackName].apply(null, args)

apply() function, .

, eval ( ).

+10

eval. window:

var callbackfunction= window[json.callback.callbackName];

, JavaScript, . :

callbackfunction.call(window, json.callback.callbackParams.param1, json.callback.callbackParams.param2);

(window this, .)

callbackParams :

callbackParams: [1, 2]

apply :

callbackfunction.apply(window, json.callback.callbackParams);
+1

All Articles