javascript对象拷贝

 

浅拷贝


 

 

浅拷贝函数:

function copy(p){
    var c = {};
    for (var i in p){
        c[i] = p[i];
    }
    c.uber = p;
    return c;
}

 

测试:

var People = {
  nation:'中国'
};
People.birthPlaces = ['北京','上海','香港'];

var Teacher = copy(People);
Teacher.birthPlaces.push('厦门');
console.log(Teacher.birthPlaces);
console.log(People.birthPlaces);
console.log(Teacher.nation);
console.log(People.nation);

 

结果:

["北京", "上海", "香港", "厦门"] 
["北京", "上海", "香港", "厦门"]  //People的birthPlaces变了
中国
中国 

 

深拷贝


 

 

深拷贝函数:

//深拷贝(递归调用浅拷贝)
function deepCopy(p, c) {
    var c = c || {};
    for (var i in p) {
      if (typeof p[i] === 'object') {
        c[i] = (p[i].constructor === Array) ? [] : {};
        deepCopy(p[i], c[i]);
      } else {
         c[i] = p[i];
      }
    }
    return c;
}

 

测试:

var People = {
  nation:'中国'
};
People.birthPlaces = ['北京','上海','香港'];

var Teacher = deepCopy(People);
Teacher.birthPlaces.push('厦门');
console.log(Teacher.birthPlaces);
console.log(People.birthPlaces);
console.log(Teacher.nation);
console.log(People.nation);

 

结果:

["北京", "上海", "香港", "厦门"] VM211:22
["北京", "上海", "香港"] VM211:23
中国 VM211:24
中国 

 

 

 参考:http://www.ruanyifeng.com/blog

 

posted @ 2014-05-21 16:50  wishyouhappy  阅读(462)  评论(0编辑  收藏  举报