xyz-data / redux-seeds

Redux Seeds : React family's all in one!
MIT License
0 stars 0 forks source link

JS Deep Clone & Shallow Clone #7

Open xgqfrms-GitHub opened 7 years ago

xgqfrms-GitHub commented 7 years ago

JS Deep Clone & Shallow Clone

浅克隆(不含原型)

Shallow Clone (excluding prototype)


// ES6 ...spread
let aClone = { ...a };

// ES5 Object.assign()
let aClone = Object.assign({}, a);

深克隆(含原型)

Deep Clone (including prototype)

xgqfrms-GitHub commented 7 years ago

https://stackoverflow.com/questions/184710/what-is-the-difference-between-a-deep-copy-and-a-shallow-copy

https://we-are.bookmyshow.com/understanding-deep-and-shallow-copy-in-javascript-13438bad941c

xgqfrms-GitHub commented 7 years ago

Deep copy & Shallow copy


// Deep copy & Shallow copy

const employeeOriginal = {
    name: 'Manjula',
    age: 25,
    Profession: 'Software Engineer'
};

//Shallow copy!
const employeeShallow = employeeOriginal; 
console.log(`employeeShallow.name`, employeeShallow.name);
console.log(`employeeOriginal`, employeeOriginal.name);

employeeShallow.name = 'Shallow Name';
console.log(`employeeShallow.name`, employeeShallow.name);
console.log(`employeeOriginal`, employeeOriginal.name);

//Deep copy!
const employeeDeep = {
    name: employeeOriginal.name,
    age: employeeOriginal.age,
    Profession: employeeOriginal.Profession
}; 
console.log(`employeeDeep.name`, employeeDeep.name);
console.log(`employeeOriginal`, employeeOriginal.name);

employeeShallow.name = 'Deep name';
console.log(`employeeDeep.name`, employeeDeep.name);
console.log(`employeeOriginal`, employeeOriginal.name);

bad, change origin value

image

good, a fully new copy!

image