Skip to content

Instantly share code, notes, and snippets.

@kwoktung
Last active March 1, 2020 10:46
Show Gist options
  • Save kwoktung/730fbe2f4bd1180f083d5db168d17010 to your computer and use it in GitHub Desktop.
Save kwoktung/730fbe2f4bd1180f083d5db168d17010 to your computer and use it in GitHub Desktop.
deep Copy
/*
Object.getPrototypeOf
Object.setPrototypeOf
也可以用来处理 原型相关的事物
*/
function deepCopy(obj, m = new WeakMap()){
let type = Object.prototype.toString.call(obj)
if (m.has(obj)) { return m.get(obj) }
switch (type) {
case '[object Null]':
case '[object Undefined]':
case '[object Number]':
case '[object String]':
case '[object Function]':
case '[object Symbol]':
return obj
case '[object Date]':
return new Date(obj)
case '[object RegExp]':
return new RegExp(obj)
case '[object Array]':
{
let ret = []
m.set(obj, ret)
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
ret[key] = deepCopy(obj[key], m)
}
}
return ret
}
case '[object Object]':
{
let ret = {}
let isPlainObj = function(obj) {
const proto = Object.getPrototypeOf(obj)
return proto === Object.prototype || proto === null
}
if (!isPlainObj(obj)) {
ret = Object.create(obj.constructor.prototype)
/*
Object.create is undefined
let F = function() {}
F.prototype = obj.constructor.prototype
ret = new F()
OR
Object.setPrototypeOf(ret, obj.constructor.prototype)
*/
}
m.set(obj, ret)
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
ret[key] = deepCopy(obj[key], m)
}
}
return ret
}
default:
return obj
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment