pass function in json and execute

前端 未结 7 1921
夕颜
夕颜 2020-11-28 07:15

Is there any way that I can pass a function as a json string (conversion with JSON.stringify), send it to another function, parse the json and then execute the function that

7条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-28 08:18

    Yes, you can convert a function to a string with it's toString() method.

    Here's an example to show converting a function to a string and back to a function:

    var myfunc = function () {
        alert('It works!');
    }
    
    var as_string = myfunc.toString();
    
    as_string = as_string.replace('It works', 'It really works');
    
    var as_func = eval('(' + as_string + ')');
    
    as_func();
    

提交回复
热议问题