// var newObj1 = oldObj; // newObj1.name = "王伏虎"; // console.log(newObj1, "--", oldObj); // 拷贝的是地址,浅拷贝; // 手写深拷贝的方法 function deepCopy(obj) { if (typeof obj !== "object" || obj == null) return obj; var target; if (obj instanceof Array) target = [] else target = {} for (var i in obj) { if (obj.hasOwnProperty(i)) { target[i] = deepCopy(obj[i]) } } return target; } var oldObj = { "name": "王降龙", "age": 18, "title": "降龙十八掌", class: [{ aa: 111 }], other: { girlFriend: null } } var newObj2 = deepCopy(oldObj); newObj2.name = ‘王伏虎‘; console.log(newObj2, "--", oldObj); // 拷贝的是内存的值,深拷贝; function newCart(name) { this.name = name; } newCart.prototype = { lunzi: 4, yushua: 1, qiyou: true, } var dazhong = new newCart(‘dazhong‘); var baoma = new newCart(‘baoma‘); // baoma.__proto__.lunzi = 5; // // dazhong.__proto__ = baoma.__proto__; // dazhong.__proto__ = deepCopy(baoma.__proto__); // 不進行深拷貝就是5 // console.log(dazhong.lunzi); //这样就是4啦 // console.dir(dazhong)
如果不想拷貝原型的值的話記得加上下面這個判斷哦!
原文:https://www.cnblogs.com/coderwhytop/p/14797356.html