Extending Objects with jQuery.extend - J Query

You have developed a plugin and need to provide default options allowing end users to overwrite them.



In this recipe, we use the $.extend() method provided by jQuery. $.extend() will return a reference to the first object passed in with the latter objects overwriting any properties they define. The following code demonstrates how this works in practice:

This allows for myPlugin() in our recipe to accept an options object that will overwrite our default settings. The following code shows how an end user would overwrite the default CSS color setting:

One special case of the $.extend() method is that when given a single object, it will extend the base jQuery object. Thus, we could define our plugin as follows to extend the jQuery core:

$.extend() also provides a facility for a deep (or recursive) copy. This is accomplished by passing in Boolean true as the first parameter. Here is an example of how a deep copy would work:

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

J Query Topics