Requirement description: Store a function in localStorage, and then pull out to execute the function.

Step 1: Convert the function to a string (save the function directly, localstorage. setItem converts the value to a string by default). , stored in localStorage;

    function test() {
        console.log('test')}const funStr = test.toString()
    
    window.localStorage.setItem('fun', funStr)
Copy the code

Step 2: Fetch the function in string form from localStorage, go back to function form, and execute (note: return is followed by a space).

    const str = window.localStorage.getItem('fun')
    const fun = new Function('return ' + str)()
    fun()
Copy the code