简体   繁体   English

将函数作为变量存储在localStorage中

[英]Store function as variable in localStorage

I'm trying to store functions in localStorage 我正在尝试将功能存储在localStorage中

class Data extends Component {
    constructor(props);
    var func = {
         f1 : this.f1.bind(this),
         f2 : this.f1.bind(this)
     }
    localStorage.setItem("method",func);

     f1(var id){
      console.log("F1" : id);
     }
     f2(var id){
      console.log("F2" : id);
     }
 }

 class App extends Component{
  constructor(props){
       super(props);
       var m = localStorage.getItem("method");
       m.f1(1);
       m.f2(3);

  }

I get error "m.f1" is not a function. 我收到错误“ m.f1”不是一个函数。 Is it possible to fix that, or is what i'm trying to do impossible ? 有可能解决这个问题,还是我要做的是不可能的? I want to do it to separate function and component for clarity (to avoid having too long code, and because i use the same function in different components), but it's not necessary 为了清晰起见,我想将功能和组件分开(以避免代码太长,并且因为我在不同的组件中使用相同的功能),但这不是必需的

What you can do is to store the function definition as a string in localStorage and then evaluate it using the eval method but it does not mean that you are storing the actual function, you are just storing a string and later you are running it as JavaScript code using eval . 您可以做的是将函数定义作为字符串存储在localStorage ,然后使用eval方法对其求值,但这并不意味着您要存储实际的函数,只是存储一个字符串,然后再将其作为JavaScript运行使用eval代码。

eg 例如

var c = console;

localStorage.setItem("itm", "(function(){ return c})()");

eval(localStorage.getItem("itm")).log("Hello!");

In the above example the c object must be accessible from where you run eval else it will not work because its just a string. 在上面的示例中,必须可以从运行eval位置访问c对象,否则它将不起作用,因为它只是一个字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM