如何以对象形式在eval中传递参数? [英] How to pass parameters in eval in an object form?

查看:605
本文介绍了如何以对象形式在eval中传递参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个json,当我得到这个json时,我需要运行回调对象附带的函数.

{
    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 
    } 
} 
}

所以根据这个我需要运行它:

getServices(1,2);

我可以使用类似eval的功能来做到这一点:

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

我可以通过将它放入for in并将参数写入字符串来实现此目的的自动化,但是我不认为这是最好的方法.

有没有一种方法可以从var中分配函数名称并将其参数作为对象提供,在我的情况下,例如:

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

我知道这不是做到这一点的方法,但这是我想学习的方法.

谢谢,思南.

解决方案

取决于要调用的函数的定义位置(全局范围或局部范围).

如果是全局的,则不需要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()函数. /p>

如果它在本地范围内,则您需要eval(您的状态如何).

I have this json, and when i get this json i need to run the function which comes at 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 that with eval function like:

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

i can automate this by putting it into a for in and writing parameters to a string, but i dont think this is the best way to go.

is there a way to assign function name from a var and giving its parameters as an object, in my case like:

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

i know this is not the way to do it but it is what i want to learn.

Thanks, Sinan.

解决方案

Depends on where the function to call is defined (global scope or a local scope).

If global, you don't need eval (and it's safer to avoid it), you just reference the function through the global window object:

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

See the apply() function used above.

If it's in a local scope, then you need the eval (how you have it is fine).

这篇关于如何以对象形式在eval中传递参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆