util.js
786 Bytes
/**
* 深克隆 所有原型链上的对象和属性
* 例: const bar=deepClone(foo)
* console.log(bar===foo) false
* @param {*} obj
*/
export const deepClone = function(obj) {
// Handle the 3 simple types, and null or undefined or function
if (obj == null || typeof obj !== "object") return obj;
// Handle Date
if (obj instanceof Date) {
const copy = new Date();
copy.setTime(obj.getTime());
return copy;
}
// Handle Array or Object
if ((obj instanceof Array) | (obj instanceof Object)) {
const copy = obj instanceof Array ? [] : {};
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) {
copy[attr] = deepClone(obj[attr]);
}
}
return copy;
}
throw new Error("Unable to clone obj! Its type isn't supported.");
};