Javascript 可以通过JSON传递JS回调吗?

Javascript 可以通过JSON传递JS回调吗?,javascript,jquery,callback,Javascript,Jquery,Callback,我意识到我不能通过JSON传递函数对象,有没有其他方法可以通过JSON传递回调函数 window.onpopstate = function(e) { var state = e.state; switch(state['method']) { case 'updateFields': updateFields(state); break; } } 其中,状态的结构如下: {'method':'updateFie

我意识到我不能通过JSON传递函数对象,有没有其他方法可以通过JSON传递回调函数

window.onpopstate = function(e) {
    var state = e.state;

    switch(state['method']) {
        case 'updateFields':
            updateFields(state);
        break;
    }
}
其中,
状态
的结构如下:

{'method':'updateFields', ...}
我想卸下开关盒,直接调用函数,类似如下:

window.onpopstate = function(e) {
    var state = e.state;

    state['method'](state);
}

但是我不知道如何使它工作。

你走对了路;您需要更改的主要内容是使所有方法成为对象的一部分。然后,您可以使用方法名称直接从该对象访问该方法:

var methods = {
    updateFields: function( state ) {
        // do something with state
    },
    anotherMethod: function( state ) {
        // etc.
    }
};

window.onpopstate = function( e ) {
    var state = e.state;
    var method = methods[state.method];
    if( method ) {
        method( state );
    } else {
        console.log( "Unknown method", state.method );
    }
};

如果你发布代码,回答起来会更清晰更容易@3Dos继续重写/添加了代码示例:)而不是
if(method)
您可以使用
if(typeof method=='function')
来确定您可以实际调用它。这一点很好!假设这是在
popstate
侦听器中使用的,我假设所讨论的JSON对象是OP自己创建的
pushState
replaceState
代码。但是在更一般的情况下,
typeof
方法会更加防弹,所以感谢您提到它。我更喜欢这种方法,而不是switch方法,尽管我不喜欢我仍然必须在
方法
中定义方法。我希望有一种方法,函数不需要列出,因此本质上可以对
'popstate'
事件匿名。虽然代码中的
'popstate'
事件不知道函数是什么,但它们仍然需要集中存储在
方法
对象中。如果这有意义的话,再加上一个更干净的代码,然后使用切换用例(我最不喜欢这种情况);这就是在JavaScript中进行这种名称查找的方法。不过,它们不一定要在对象文本中定义。你可以做
var方法={}methods.updateFields=function(state){…}
如果您愿意的话。@MichaelBeary perfect这是一个更好的选择,它允许我有一个集中的
'popstate'
侦听器,并根据需要在其他js文件中定义函数:)