• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
邹天得
博客园    首页    新随笔    联系   管理    订阅  订阅
复制对象

《你不知道的JavaScript<上卷>》

/*
var someobj = {
  a:1,
  b:2
};
var ify = JSON.stringify(someobj);
var newObj = JSON.parse(JSON.stringify(someobj));
console.log(typeof ify);
console.log(typeof newObj);
console.log(ify == '{"a":1,"b":2}');
console.log(newObj);
console.log(someobj);
*/

function anotherFunction() { console.log("here."); }
var anotherObject = {
  c: true
};
var anotherArray = [1,2];

var myObject = {
  a: 2,
  b: anotherObject, // 引用, 不是复本!
  c: anotherArray, // 另一个引用!
  d: anotherFunction
};

// ES6 定义了 Object.assign(..) 方法来实现浅复制
var newObj = Object.assign({}, myObject);
console.log(newObj.a);//2
console.log(newObj.b == anotherObject);//true
console.log(newObj.c == anotherArray);//true
console.log(newObj.d == anotherFunction);//true

console.log(newObj.b);//Object {c: true}
console.log(newObj.c);//[1, 2]
console.log(newObj.d);//function anotherFunction() { console.log("here."); }


/***************************************/
var ify = JSON.stringify(myObject);
var newObj_1 = JSON.parse(ify);
console.log(newObj_1);//丢失d属性
console.log(myObject);

console.log(newObj_1.a);//2
console.log(newObj_1.b == anotherObject);//false
console.log(newObj_1.c == anotherArray);//false
console.log(newObj_1.d == anotherFunction);//false

console.log(newObj_1.b);//Object {c: true}
console.log(newObj_1.c);//[1, 2]
console.log(newObj_1.d);//undefined

posted on 2017-03-30 00:24  邹天得  阅读(117)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3