Created
January 20, 2017 18:54
-
-
Save solominh/4cf9899bb99134c3bec7f750347ac7d3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function copy(obj) { | |
var copy = Object.create(Object.getPrototypeOf(obj)); | |
var propNames = Object.getOwnPropertyNames(obj); | |
propNames.forEach(function (name) { | |
var desc = Object.getOwnPropertyDescriptor(obj, name); | |
Object.defineProperty(copy, name, desc); | |
}); | |
return copy; | |
} | |
// Object test | |
var obj1 = { a: 1, b: 2 }; | |
var obj2 = copy(obj1); | |
// obj2 looks like obj1 now | |
// Array test | |
var arr = [] | |
var arr1 = [1, 2, arr] | |
var arr2 = copy(arr1) | |
// Shalow copy test | |
arr2.push(2) // => only affect arr2 | |
// Deep copy test | |
arr.push(1) // => affecting both arr1 and arr2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment