# 第 49 题：如何实现一个对象深拷贝？

``````let a = {
age: 20
};

let b = a;

b.age = 30;

console.log(a.age); // 30``````

### 利用 JSON 类

``````let a = {
age: 20
};

let b = JSON.parse(JSON.stringify(a));

b.age = 30;

console.log(a.age); // 20``````

``````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``````

### 利用递归的方式

dfs-deep-copy.js

``````// 深度优先遍历
let dfs = data => {
let newData;

if (type(data) === 'array') {
newData = [];
data.map((item, index) => {
newData[index] = dfs(item);
});
} else if (type(data) === 'object') {
newData = {};
Object.keys(data).map(item => {
newData[item] = dfs(data[item]);
});
} else {
newData = data;
}

return newData;
};

// 类型字典
export let type = data => {
let dist = {
'[object Array]': 'array',
'[object Object]': 'object',
'[object Number]': 'number',
'[object Function]': 'function',
'[object String]': 'string',
'[object Null]': 'null',
'[object Undefined]': 'undefined'
};

return dist[Object.prototype.toString.call(data)];
};

export default dfs;``````

index.vue

``````
import dfs from './dfs-deep-copy.js';

export default {
mounted() {
let a = {
age: 20,
local: function() {
return 5;
}
};

let b = dfs(a);
b.local = function() {
return 10;
};

console.log(b.local()); // 10
console.log(a.local()); // 5
}
};
``````