利用JSON类
就是将一个对象转为JSON字符串,在转回JSON对象
let a = {
age: 20
};
let b = JSON.parse(JSON.stringify(a));
b.age = 30;
console.log(a.age); // 20
优点:优点是方便快捷,性能相对比较好
缺点:但是复杂的对象进行JSON转换有可能会丢失属性,如下代码
let a = {
age: 20,
local: function() {
return 5;
}
};
let b = JSON.parse(JSON.stringify(a));
console.log(b); // { age : 20 }
console.log(b.local()); // b.loacl is not a function