我意识到我无法通过 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/