Search code examples
javascriptjsonobject

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!


Solution

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