JSON.stringify function

后端 未结 5 878
谎友^
谎友^ 2020-11-27 04:56

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

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

5条回答
  •  自闭症患者
    2020-11-27 05:41

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

提交回复
热议问题