天天看點

javascript序列化導緻資料丢失

我們知道的序列化會導緻方法丢失,那是有其他的影響呢?通過下面簡單的例子一起看一下

class Custom{
    constructor(){
        this.custom1 = 1 
    }
    customFn(){
        console.log('hello, my name is custom')
    }
}
let custom = new Custom();
let obj = {
    a: 'a',
    b: function() {
        console.log('b')
    },
    c: undefined,
    d: null,
    e: custom,
    f: Custom,
    g: [custom, undefined, 123, Custom,  function() {
        console.log('b')
    }],
    h: {
        custom, undefined, "123": 123, Custom, function() {
            console.log('b')
        }
    }
}
console.log(JSON.stringify(obj))

// {
//     "a": "a",
//     "d": null,
//     "e": {
//         "custom1": 1
//     },
//     "g": [
//         {
//             "custom1": 1
//         },
//         null,
//         123,
//         null,
//         null
//     ],
//     "h": {
//         "123": 123,
//         "custom": {
//             "custom1": 1
//         }
//     }
// }
           

由此可見 對象序列化時,方法、undefined、類都消失了,數組中他們相應的位置也皆為null了

繼續閱讀