/** * 浅拷贝 * @type {{address: {name: string}, sex: number, name: string}} */ let person1 = { sname: 'tommy' } let person2 = person1; person2.sname = 'hello,tommy!' console.log(person2.sname) // hello,tommy! console.log(person1.sname) //hello,tommy! /** * 深拷贝 * @type {{address: {name: string}, sex: number, name: string}} */ let person = { name: 'jack', sex: 6, address: { name: '陕西西安' } } var person3 = deepCopy(person); person3.address.name = '新疆乌鲁木齐' console.log(person3) // { name: 'jack', sex: 6, address: { name: '新疆乌鲁木齐' } } console.log(person) // { name: 'jack', sex: 6, address: { name: '陕西西安' } } function deepCopy(obj = {}) { let result if (typeof obj != "object" || obj == null) { return obj } if (obj instanceof Array) { result = [] } else { result = {} } for (let key in obj) { result[key] = deepCopy(obj[key]) } return result }