Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
84 views
in Technique[技术] by (71.8m points)

javascript - JSON.stringify function

I have an object that has some properties and methods, like so:

{name: "FirstName",
age: "19",
load: function () {},
uniq: 0.5233059714082628}

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".

Is there any way to stringify and object and maintain the methods it has?

Thanks!

question from:https://stackoverflow.com/questions/6754919/json-stringify-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...