jQuery Default / JavaScript Default Options

8 Feb 2011 Ferado

This blog is more for myself than any of you readers out there. Every so often I need to have an object of some kind or a function that has its own defaults. Here’s how to do it using jQuery:

[cc lang=”javascript”]

// function
function myFunc(options) {
var defaults = {option1: ‘val’, option2: ‘val2’};
var settings = $.extend({}, defaults, options);
// do something
}

// or, an object
var myObj = {
init: function(options) {
var defaults = {option1: ‘val’, option2: ‘val2’};
var settings = $.extend({}, defaults, options);
}
};

[/cc]

Conclusion

It’s easier to remember how to do things when you practice them. This was my practice at setting JavaScript defaults. See the reference link for more, it’s a good one.