有没有可能让 JSON.stringify 保留功能? [英] Is there any possibility to have JSON.stringify preserve functions?

查看:48
本文介绍了有没有可能让 JSON.stringify 保留功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

拿这个对象:

x = {
 "key1": "xxx",
 "key2": function(){return this.key1}
}

如果我这样做:

y = JSON.parse( JSON.stringify(x) );

然后 y 将返回 { "key1": "xxx" }.有什么办法可以通过 stringify 传递函数吗?使用ye goode olde eval()"可以创建带有附加函数的对象,但是打包它有什么用?

Then y will return { "key1": "xxx" }. Is there anything one could do to transfer functions via stringify? Creating an object with attached functions is possible with the "ye goode olde eval()", but whats with packing it?

推荐答案

您不能打包函数,因为它们关闭的数据对任何序列化程序都是不可见的.即使是 Mozilla 的 uneval 也无法正确打包闭包.

You can't pack functions since the data they close over is not visible to any serializer. Even Mozilla's uneval cannot pack closures properly.

最好的办法是使用恢复剂和替代品.

Your best bet, is to use a reviver and a replacer.

https://yuilibrary.com/yui/docs/json/json-freeze-thaw.html

传递给 JSON.parse 的 reviver 函数应用于原始解析对象中从最深键到最高级的所有键:值对.在我们的例子中,这意味着名称和发现的属性将通过 reviver,然后包含这些键的对象将通过.

The reviver function passed to JSON.parse is applied to all key:value pairs in the raw parsed object from the deepest keys to the highest level. In our case, this means that the name and discovered properties will be passed through the reviver, and then the object containing those keys will be passed through.

这篇关于有没有可能让 JSON.stringify 保留功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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