jQuery: cloning objects

While studying the source code of Prototype, I discovered that Prototype clones objects by passing an empty object as the first parameter of its extend method. This allows us to get an exact copy of the source object without affecting the original. Since also jQuery has a similar method, called $.extend, I've tried a similar approach by creating a global jQuery function called $.clone that performs an almost identical action. Its code is as follows:

(function($) {

  $.clone = function(source) {
  
   var cloned = $.extend({}, source);
   
   return cloned; 
  
  
  };


})(jQuery);

Let's create a simple test object:

var Class = {
    
    property: 'Test',
    method: function() {

      return this.property + ' OK';

    }
};

Now we can clone it and check out whether the cloning has been successful or not:

var clone = $.clone(Class);
alert(clone.method()); // Test OK

It works! Let's see if the cloning operation did affect the original object:

clone.method = function() {
  
    return 'Test';
  
};
  
alert(clone.method()); // Test
alert(Class.method()); // Test OK

As you can see, even though we've overridden the method of the object's copy, the original method remains untouched, as expected.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.