KineticJS object with added property to JSON

2019-09-16 06:40发布

问题:

I am trying to serialize KineticJS object (with one added property) to JSON, but if I call the JSON.stringify(test);, it returns only JSON representation of KineticJS object without my added property. Does anybody know, where could be a problem, please?

 test = new Kinetic.Line(
                {
                    points : [ 29, 30, 31, 32 ],
                    stroke : 'black',
                    strokeWidth : 2,
                    lineJoin : 'round',
                    id : '#line'
                });
 test.obj = "my own property";
 JSON.stringify(test);

returns

{"attrs":{"points":[{"x":29,"y":30},{"x":31,"y":32}],"stroke":"black","strokeWidth":2,"lineJoin":"round","id":"#line"},
"nodeType":"Shape","shapeType":"Line"}"

But I need also information about test.obj..

回答1:

You can do this like that :

var test = new Object();

test.kinetic = new Kinetic.Line(
                {
                    points : [ 29, 30, 31, 32 ],
                    stroke : 'black',
                    strokeWidth : 2,
                    lineJoin : 'round',
                    id : '#line'
                });
 test.obj = "my own property";
 console.log(JSON.stringify(test));