JSON.stringify 更改属性

JSON.stringify changing properties

https://jsfiddle.net/6CDFr/229/

function testing() {
  foo = canvas.getObjects();
  bar = JSON.stringify(canvas.getObjects());
  console.log(foo);
  console.log(bar);
}

JSON.stringify() 正在改变 "x1"、"y1"、"x2" 和 "y2" 属性,详见我的 JSFiddle link以上,我不确定为什么。

来自 JSON.stringify (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#toJSON_behavior)

的 (Mozilla) 文档

toJSON() behavior

If an object being stringified has a property named toJSON whose value is a function, then the toJSON() method customizes JSON stringification behavior: instead of the object being serialized, the value returned by the toJSON() method when called will be serialized. For example:

如果你使用下面的,你应该得到相似的值

function testing() {
    foo = canvas.getObjects()[0];
    bar = JSON.stringify(canvas.getObjects()[0]);
    console.log(foo.toJSON());
    console.log(bar);
}

或者如果你将 toJSON 属性 设置为未定义(但我很确定这会对 fabric.js 造成严重破坏,除非你在对象的副本上这样做 - 我已经直接在下面的对象上完成)

function testing() {
    foo = canvas.getObjects();
    bar = JSON.stringify(canvas.getObjects().map(function (o) {
        o.toJSON = undefined;
        return o
    }));
    console.log(foo);
    console.log(bar);
}