《你不知道的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
浙公网安备 33010602011771号