How do I clone/copy an instance of an object in CoffeeScript?

10,836

Solution 1

This 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 deep clone an object in JavaScript?

Solution 2

Thanks to Larry Battle for the hint:

John Resig's solution of using jQuery.extend works brilliantly!

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

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

More information can be found in the jQuery documentation.

Solution 3

From The CoffeeScript Cookbook:

http://coffeescriptcookbook.com/chapters/classes_and_objects/cloning

Underscore.js also has a shallow clone function:

http://underscorejs.org/#clone

Share:
10,836
Chris Nolet
Author by

Chris Nolet

Software Engineer at Apple, Co-Founder of App.io

Updated on June 05, 2022

Comments

  • Chris Nolet
    Chris Nolet almost 2 years

    Fairly straight forward question but Googling hasn't turned up anything as yet.

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

    Does CoffeeScript offer a simpler solution?