File tree Expand file tree Collapse file tree 1 file changed +62
-0
lines changed Expand file tree Collapse file tree 1 file changed +62
-0
lines changed Original file line number Diff line number Diff line change
1
+ ---
2
+ layout: recipe
3
+ title: Cloning an object (deep copy)
4
+ chapter: Objects
5
+ ---
6
+
7
+ h2. Problem
8
+
9
+ You want to clone an object with all its sub-objects
10
+
11
+ h2. Solution
12
+
13
+ {% highlight coffeescript %}
14
+ clone = (obj) ->
15
+ if not obj? or typeof obj isnt 'object'
16
+ return obj
17
+
18
+ newInstance = new obj.constructor()
19
+
20
+ for key of obj
21
+ newInstance[key] = clone obj[key]
22
+
23
+ return newInstance
24
+
25
+ x =
26
+ foo: 'bar'
27
+ bar: 'foo'
28
+
29
+ y = clone(x)
30
+
31
+ y.foo = 'test'
32
+
33
+ console.log x.foo isnt y.foo, x.foo, y.foo
34
+ # => true, bar, test
35
+ {% endhighlight %}
36
+
37
+ h2. Discussion
38
+
39
+ The difference between copying an object through assignement and through this
40
+ clone-function is how they handle references.
41
+ The assignement only copies the object's reference, whereas the clone-function
42
+ creates a complete new object by
43
+ * creating a new object like the source object,
44
+ * copying all attributes form the source object to the new object and
45
+ * repeating these steps for all sub-objects by calling the clone-function
46
+ recursively.
47
+
48
+ Example of an assignement copy:
49
+ {% highlight coffeescript %}
50
+ x =
51
+ foo: 'bar'
52
+ bar: 'foo'
53
+
54
+ y = x
55
+
56
+ y.foo = 'test'
57
+
58
+ console.log x.foo isnt y.foo, x.foo, y.foo
59
+ # => false, test, test
60
+ {% endhighlight %}
61
+
62
+ As you can see, when you change `y` after the copy, you also change `x`.
You can’t perform that action at this time.
0 commit comments