是否有可能让JSON.stringify保存功能? [英] Is there any possibility to have JSON.stringify preserve functions?
问题描述
使用此对象:
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函数应用于从最深的密钥到最高级别的原始解析对象中的所有key:value对.在我们的例子中,这意味着名称和发现的属性将通过齐整器传递,然后包含这些键的对象将通过.
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屋!