underscore.js is a javascript utility library.
Let us understand the extend method of this very useful library.
_.extend is for extending a given object with all the properties of the passed-in object(s)
Here is an example, we have three objects aObj, bObj, cObj and we want to combine them into single object.
Using _.extend is a simple way of combining these objects. And before trying out the example don't forget to import the underscore.js library
Now access the source code of underscore.js and look for the extend method. This is how it looks like
This uses functional programming style.
createAssigner takes two inputs and returns a function. The two inputs are
(1) keysFunc
(2) defaults
Since it is returning a function, so a closure is formed, and the returned function remembers the two inputs
Looking at the source code from the line (keys = keysFunc(source)) it is evident that keysFunc is a function itself.
And from the line _.extend = createAssigner(_.allKeys) we can understand that allKeys is the function that is passed as input for keysFunc. Here is the allKeys function from underscore.js
To the function that is returned by createAssigner, we pass the objects whose properties have to be combined as the inputs. In our example aObj, bObj and cObj are passed to the return function of createAssigner function.
aObj is the source object, bObj and cObj are the objects that have to be merged with aObj.
Note that extend mutates the aObj. The resultant aObj has the properties from all the objects passed for merging with aObj
Comments
Post a Comment