I am cloning an array of objects using slice()
but when I pass that cloned array into another method the array's contents are losing their references and become undefined
.
class Chooser
constructor: (@order, @items) ->
# do stuff
choose: ->
console.debug "Choosing", @order.size, "from", @items.slice()
@process(@order.size, @items.slice())
# do stuff
process: (count, items) ->
console.debug "count", count
console.debug "items", items
console.debug "@items", @items
# do recursive stuff that includes an items.shift()
The first console.debug
gives me, as expected:
Choosing 10 items from [Item, Item]
where Item
and Item
are exactly what I expected.
But then the next console.debug
lines give me
count 10
items [undefined x 2]
@items [Item, Item]
I understand that @items.slice()
creates a shallow copy of @items
, and as such the objects within the array are references to the same Item
objects. The Item
objects obviously still exist as they are still in the original @items
array.
Why, do the objects in the cloned array seem to lose their references once within the process
method?
See this Working example of the problem converted to Javascript