How to clone / copy an instance of an object in CoffeeScript?

Pretty straightforward question, but Googling hasn't found anything yet.

How to copy / clone / duplicate an instance of an object in Coffeescript? I could always create a method clone()that returns a new instance with the copied values, but this seems like an error-prone way to do this.

Does CoffeeScript offer a simpler solution?

+5
source share
3 answers

That might work.

clone = (obj) ->
  return obj  if obj is null or typeof (obj) isnt "object"
  temp = new obj.constructor()
  for key of obj
    temp[key] = clone(obj[key])
  temp

Adopted from: What is the most efficient way to deeply clone an object in JavaScript?

+8
source

Thanks to Larry Battle for the hint:

Solution using jQuery.extend John Resig works brilliantly!

// Shallow copy
newObject = $.extend({}, oldObject);

// Deep copy
newObject = $.extend(true, {}, oldObject);

jQuery.

+5

All Articles