Extending objects with JQuery.extend

Extending objects with JQuery.extend

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

(function($) {
   $.fn.myPlugin = function(options) {
        options = $.extend({
            message: ‘Hello world’,
            css: {
                color: ‘red’
        }, options);
        return this.each(function() {

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.

$.extend() also provides a facility for a deep (or recursive) copy. This is accomplished by passing in Boolean true as the first parameter.

Back to top