js函数转字符串存储再转回函数执行

732 阅读1分钟

需求描述:将一个函数存于localStorage中,再取出来执行这个函数。

步奏一:将函数转为字符串(这里可以不转,直接保存函数,localStorage.setItem默认会把value转为字符串。),在存于localStorage中;

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

步奏二:从localStorage中取出字符串形式的函数,再转回函数形式,最后执行(注意点: return后面有一个空格)。

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