Friday, November 1, 2013

I faced this issue a while back that I wanted to achieve something like

var a,b,c;
a = b + c;

for object literals in Javascript. Moreover to that, I wanted to have an option to extend (merge, add or whatever you might want to call it) in a loop, something like the following for the string type:

I first tried to write my own code and then suddenly found a better solution: jQuery's extend method. In short, jQuery's extend method extends N objects into a target object:

jQuery.extend( target [, object1 ] [, objectN ] )

The target is an object that will receive the new properties, Object1 is an object containing additional properties to merge in and finally, objectN is the additional objects containing properties to merge in. One way of using the function is like following:

You could also use the method to extend an object recursively, within a loop for example and that is why I highly recommend you to use this method. If you want to extend the objects recursively, make target the return value of the method, like the code below: