JS - 数据类型的值拷贝函数(深拷贝)

时间:2021-06-17 14:02:14
function mottoClone (obj) {
  if (obj === null || typeof obj !== 'object') return obj;
  if (obj instanceof Boolean) return new Boolean(obj.valueOf());
  if (obj instanceof Number) return new Number(obj.valueOf());
  if (obj instanceof String) return new String(obj.valueOf());
  if (obj instanceof RegExp) return new RegExp(obj.valueOf());
  if (obj instanceof Date) return new Date(obj.valueOf());
  var cpObj = obj instanceof Array ? [] : {};
  for (var key in obj) cpObj[key] = myClone(obj[key]);
  return cpObj;
}

支持的数据类型或格式有:Boolean,Number,String,RegExp,Date,Function,Array,JSON
支持深拷贝(循环迭代),如:
var obj = {
id: 1,
name: 'xxx',
sayName: function () {
console.log('my name is' + this.name);
},
childs: [
{},
{},
...
],
opts: {
xxx: [],
...
},
...
};
var newObj = mottoClone(obj);