4 creative ways to clone objects
This is a somewhat simple function that will clone an object and return the clone. If a non-object value is passed in, that value is returned.
If you try the above function, you’ll see that once bob has been cloned as bill, modifying values on bill won’t change the original values on bob.
2) A clever exploit of the JSON library to deep-clone objects
We can exploit the JSON library for a rather fast way of deep-cloning objects. Check it out:
This method is nice and fast (faster as a rule than the jQuery method and possibly the Mootools function as well), and certainly rather less code than the first example. Plus, it’s pretty clever–just make sure you add a comment explaining what you’re doing. Otherwise, it could cause quite a bit of confusion!
3) Using jQuery’s $.extend() function
jQuery has a method that can be used to deep-clone objects, the $.extend() function. Let’s take a look at how it can be used:
Pretty handy, eh? This method is a little slower than the JSON exploit, but that shouldn’t really be a problem when you’re only doing a few clones. If you’re doing hundreds or thousands of clones, it might be time to think about the JSON exploit or another solution.
4) Using Mootools’ clone() function to clone objects