jQuery “extend” as an Object Merger

Let’s say you’re creating a class and want to load in some “options”. You could write you’re own defaults and up with a huge top heavy class…or you could let jQuery do the work for you.

[pastacode lang=”javascript” message=”” highlight=”” provider=”manual”]

function MyClass($, options) {
    
    var __ = this;
    
    var defaults = {
        // callback
        onResult: function(data) {},
        // attribute
        color: 'red'
    };
    __.options = $.extend({}, defaults, options || {});
    
}

// red
var mc = new MyClass(jQuery);

// black
var black = new MyClass(jQuery, {color: 'black'});

[/pastacode]

Simps.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.