Last active
August 29, 2015 14:21
-
-
Save hellowin/f89febd25e07ae17e02c to your computer and use it in GitHub Desktop.
Javascript Copy Object Reference
This file contains hidden or 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
| // using constructor to clone object | |
| var A = function(){ | |
| this.array = ['a','b','c']; | |
| }; | |
| var a = new A(); | |
| console.log(a.array); | |
| // ["a", "b", "c"] | |
| var b = new A(); | |
| b.array.push('d'); | |
| console.log(b.array); | |
| // ["a", "b", "c", "d"] |
This file contains hidden or 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
| // using function factory to clone object | |
| var factoryA = function(){ | |
| return ['a','b','c']; | |
| }; | |
| var a = factoryA(); | |
| console.log(a); | |
| // ["a", "b", "c"] | |
| var b = factoryA(); | |
| b.push('d'); | |
| console.log(b); | |
| // ["a", "b", "c", "d"] |
This file contains hidden or 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
| // most easy way to clone object | |
| var a = ['a','b','c']; | |
| var b = JSON.parse(JSON.stringify(a)); | |
| b.push('d'); | |
| console.log(a); | |
| // ["a", "b", "c"] | |
| console.log(b); | |
| // ["a", "b", "c", "d"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment