Is there a function or library that will take a JS Object that has properties and functions and stringify it to JSON but when it comes to a Function, it will change it into a property and call the function to return its value??
function object() {
this.property = 12;
this.function = function() { return "This"; }
}
So this would stringify into:
{property: 12, function: "This"}
Any ideas? Just curious if there is one already.. if not I will take a stab at one. It shouldn't be to hard to extend a JSON.stringify().开发者_C百科
Some objects have no trivial serialization. If you wish you serialize them, you must do so yourself with you own set of assumptions.
Functions (esp. those with closures) and IO Streams are some examples. In the case of a JS function, serialization (without serializaing the entire context!) violates the semantics of the function with respect to the execution context and scope chains. Also, the ability for assistance from the browser to return the "text" of a function depends upon the browser.
The JSON.stringify
method provides the option to include a callback argument, called replacer
, the function is invoked passing the key and value of each property of your object, there you are able to detect if the value is a function
and invoke it:
var obj = {
"property": 12,
"function": function() { return "This"; }
};
JSON.stringify(obj, function (key, value) {
if (typeof value == 'function') {
return value();
}
return value;
});
精彩评论