最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I clonecopy an instance of an object in CoffeeScript? - Stack Overflow

programmeradmin6浏览0评论

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?

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?

Share Improve this question edited Jun 16, 2012 at 4:41 Larry Battle 9,1785 gold badges43 silver badges55 bronze badges asked Jun 16, 2012 at 3:48 Chris NoletChris Nolet 9,0738 gold badges69 silver badges95 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 8

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?

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.

From The CoffeeScript Cookbook:

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

Underscore.js also has a shallow clone function:

http://underscorejs/#clone

发布评论

评论列表(0)

  1. 暂无评论