gpt4 book ai didi

javascript - 是否可以通过 JSON 传递 JS 回调?

转载 作者:行者123 更新时间:2023-12-01 02:46:10 24 4
gpt4 key购买 nike

我意识到我无法通过 JSON 传递函数对象,是否有其他方法通过 JSON 传递回调函数?

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

switch(state['method']) {
case 'updateFields':
updateFields(state);
break;
}
}

其中state的结构如下:

{'method':'updateFields', ...}

我希望删除 switch case 并直接调用该函数,类似于:

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 );
}
};

关于javascript - 是否可以通过 JSON 传递 JS 回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47248085/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com