Cat.prototype = Object.create(Animal.prototype) -是深拷贝
来源:4-6 JS面向对象深层填坑—ES5
Jean0123
2018-04-04
写回答
1回答
-
傅猿猿
2018-04-05
/** * Created by 傅令杰 */ (function () { 'use strict'; const oldObj = { A: { a: 1 } }; // const newObj1 = Object.assign({}, oldObj); // newObj1.A.a = 11; // // console.log(newObj1.A.a); // console.log(oldObj.A.a); // const newObj2 = Object.create(oldObj); // newObj2.A.a = 2; // console.log(newObj2.A.a); // console.log(oldObj.A.a); const deepClone = function (oldObj) { const obj = {}; for (let i in oldObj) { let prop = oldObj[i]; if (prop === obj) { continue; } if (typeof prop === 'object') { obj[i] = (prop.constructor === Array) ? [] : Object.create(prop); } else { obj[i] = prop; } } return obj; }; const newObj3 = deepClone(oldObj); newObj3.A.a = 2; console.log(newObj3.A.a); console.log(oldObj.A.a); })();
特意给你写的例子,深拷贝的话A下的a属性更改是不会影响到原始对象的,浅拷贝则会影响,打开注释看看,测试一下
00
相似问题