It exists for the same reason as jQuery $.extend (including npm port ), and it has nothing to do with performance: to add one object to another object, thereby expanding it with another. The Lodash version allows you to have finer control over the merge process using the customizer function.
Object extensions have several uses that jQuery developers claim to write plugins for :
The improvement we can and should do for the code above is to expose the plugin’s default settings. This is important because it’s very easy for plugin users to override / configure a plugin with minimal code. And here we begin to use the functional object.
// Plugin definition. $.fn.hilight = function( options ) { // Extend our default options with those provided. // Note that the first argument to extend is an empty // object – this is to keep from overriding our "defaults" object. var opts = $.extend( {}, $.fn.hilight.defaults, options ); // Our plugin implementation code goes here. }; // Plugin defaults – added as a property on our plugin function. $.fn.hilight.defaults = { foreground: "red", background: "yellow" };
In the above example, you can clearly see that when working with a predefined object with properties that you need to expand or even overwrite with an unknown object with unknown properties, since this object is outside the control of the developer plugin
Sometimes we just don’t know what properties are on the extension object, sometimes it just makes things more readable, and sometimes it’s just inconvenient to do it manually, especially if you need deep merging.
Another application is where you want to model a simple inheritance hierarchy:
// very trivial example: var Super = { superFoo: function() {} }; var Sub1 = { sub1Foo: function() {} }; var Sub2 = { sub2Foo: function() {} }; $.extend(Sub1, Super) // now Sub1 has Super powers $.extend(Sub2, Super) // now Sub2 has Super powers too
source share