完整實現(xiàn)方法1
Es6新增的Symbol由于不是引用類型,只有深拷貝
WeakMap和WeakSet由于無法遍歷狈定,無法深拷貝
function extend(parent, children) {
var i,
toStrF = Object.prototype.toString,
strC = "[Object Array]"
children = children || {}
for (i in parent) {
if (parent.hasOwnProperty(i)) {
if (typeof parent[i] === "object") {
if(parent[i] instanceof Set) {
children[i] = new Set([...parent[i]])
} else if(parent[i] instanceof Map) {
children[i] = new Map([...parent[i]])
} else {
children[i] = (toStrF.call(parent[i]) === strC) ? [] : {};
extend(parent[i], children[i])
}
} else {
children[i] = parent[i]
}
}
}
return children
}
實現(xiàn)方法2
利用JSON.parse(JSON.stringify())做屬性拷貝,但是需注意此方法會丟失如時間對象熟掂,正則對象等
function extend(parent, children) {
children = children || {}
for( i in parent) {
if(parent.hasOwnProperty(i)) {
children[i] = parent[i]
}
}
children = JSON.parse(JSON.stringify(children))
return children
}
實現(xiàn)方法3
如果需要復制的對象屬性中沒有引用類型時硅确,可直接用...
let a = {...b}