js Object的复制

js Object为引用类型, 用=复制会造成改变一个全都变动。
以前克隆Object 是这样的(我已经不记得哪里抄了来的了):

window.clone = function (obj) {

  if (null == obj || "object" != typeof obj) return obj;


  if (obj instanceof Date) {
    var copy = new Date();
    copy.setTime(obj.getTime());
    return copy;
  }


  if (obj instanceof Array) {
    var copy = [];
    for (var i = 0, len = obj.length; i < len; ++i) {
      copy[i] = clone(obj[i]);
    }
    return copy;
  }


  if (obj instanceof Object) {
    var copy = {};
    for (var attr in obj) {
      if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
    }
    return copy;
  }

  throw new Error("Unable to copy obj! Its type isn't supported.");
}

后来还发现了奇淫巧技:

    JSON.parse(JSON.stringify(Object))

ES5:

Object.clone(Object); // 
Object.assign(Object,{});

 

posted @ 2018-02-26 17:31  抓猫的老鼠  阅读(354)  评论(0编辑  收藏  举报