将函数保存在本地存储中 [英] save a function in localstorage

查看:133
本文介绍了将函数保存在本地存储中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一些对象,这些对象包含许多要从浏览器显示和操作的数据,我想将其保存在本地存储中. 为了保存对象,我使用了JSON.stringify(),因此所有内容都变成了文本,并且效果很好

I'm working with some objects that contains a number of data to be displayed and manipulated from browser, and I want to save it in local storage. In order to save objects I used JSON.stringify() so everything become text, and it works well

{
"bindingRef": [],
"primo": {
    "name": "primo",
    "modifiable": true,
    "binded": false,
    "isInteger": false,
    "label": "Numero di Primi"
},
"secondo": {
    "name": "secondo",
    "modifiable": true,
    "binded": false,
    "isInteger": false,
    "label": "Numero di Secondi"
}
}

现在我正尝试通过将其转换为字符串然后保存它来保存函数

Now I'm trying to save also a function by converting it to a string and then saveing it

JSON.stringify(myFunction.toString());

但是输出是这个

"savedFunction": "function () {\n\t\t\t\tvar tot = menu.primo.get() * 6 + menu.secondo.get() * 8 + menu.dolce.get() * 4;\n\t\t\t\tif (menu.sconto.get()) {\n\t\t\t\t\treturn tot * 0.90;\n\t\t\t\t} else {\n\t\t\t\t\treturn tot;\n\t\t\t\t}\n\t\t\t}"

将函数保存在本地存储中是正确的方法还是有更好的方法?如果这是正确的方法,是否有一种方法可以简单地删除任何制表符/缩进字符,还是应该使用例如regexp函数来操作字符串?

Is it the correct way to save a function in local storage or is there a better way to do this? If this is the correct way, is there a way to simply remove any tabulation/indentation character or should I manipulate the string, for example using some regexp function?

推荐答案

JS中的功能就像在许多功能语言中一样都是闭包的:它们在定义时将环境范围的内容包装在其中,包括临时数据,例如db或文件句柄.

Function in JS as in many functional languages are closures: they wrap inside them the content of the environment scope at the moment of definition, including ephemeral data like db or file handles.

这不是一个好主意,因为这可能会由于JSON反序列化行为而导致问题,因此您必须检查函数中包装的内容和自定义的内容.

It's not a good idea because this can lead to problems due to JSON deserialization behaviour, so you have to check what in the function is wrapped and what is self-defined.

另请参见 SO线程.

这篇关于将函数保存在本地存储中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆