JSON.stringify 函数 [英] JSON.stringify function
问题描述
我有一个具有一些属性和方法的对象,如下所示:
I have an object that has some properties and methods, like so:
{name: "FirstName",
age: "19",
load: function () {},
uniq: 0.5233059714082628}
我必须把这个对象传递给另一个函数.所以我尝试使用 JSON.stringify(obj) 但加载函数(当然不是空的,这只是为了这个例子的目的)正在丢失".
and I have to pass this object to another function. So I tried to use JSON.stringify(obj) but the load function (which of course isn't empty, this is just for the purpose of this example) is being "lost".
有没有办法stringify
并对象和维护它拥有的方法?
Is there any way to stringify
and object and maintain the methods it has?
谢谢!
推荐答案
为什么要对对象进行字符串化?JSON 不理解函数(它不应该理解).如果您想传递对象,为什么不使用以下方法之一?
Why exactly do you want to stringify the object? JSON doesn't understand functions (and it's not supposed to). If you want to pass around objects why not do it one of the following ways?
var x = {name: "FirstName", age: "19", load: function () {alert('hai')}, uniq: 0.5233059714082628};
function y(obj) {
obj.load();
}
// works
y({name: "FirstName", age: "19", load: function () {alert('hai')}, uniq: 0.5233059714082628});
// "safer"
y(({name: "FirstName", age: "19", load: function () {alert('hai')}, uniq: 0.5233059714082628}));
// how it's supposed to be done
y(x);
这篇关于JSON.stringify 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!