vuex源码中关于js深拷贝问题

vuex中有一个工具类有如下处理深拷贝代码:

function deepCopy(obj, cache = []) {
    // just return if obj is immutable value
    if (obj === null || typeof obj !== 'object') {
        return obj
    }

    // if obj is hit, it is in circular structure
    const hit = cache.filter(c => c.original === obj)[0]
    if (hit) {
        return hit.copy
    }

    const copy = Array.isArray(obj) ? [] : {}
    // put the copy into cache at first
    // because we want to refer it in recursive deepCopy
    cache.push({
        original: obj,
        copy
    })

    Object.keys(obj).forEach(key => {
        copy[key] = deepCopy(obj[key], cache)
    })

    return copy
}

使用这个函数copy对象的时候,如果对象中某个属性的值是date类型的话,它会把date类型转成一个空对象:

let obj = {
    obj: new Date()
}
console.log(obj)
console.log(deepCopy(obj))

image.png

请问为什么会这样?怎么修改代码能修复这个问题?

待解决 悬赏分:10 - 离问题结束还有 172天22小时30分3秒
反对 0举报 0 收藏 0

我来回答

回答1