jQuery Object
Example showing a jQuery object with private and public methods.
by rustyjeans
JavaScript
(function ($) {
$.myObject = function (options) {
var opts = $.extend({}, $.myObject.defaults, options),
privateMethod = function (msg) {
alert(opts.start + ': ' + msg);
};
return {
publicMethod: function (msg) {
privateMethod(msg);
}
}
};
$.myObject.defaults = {
start: '1'
};
})(jQuery);
$(function () {
// access a public method with default settings
$.myObject().publicMethod('One');
// passing in options
$.myObject({'start': '2'}).publicMethod('Two');
// overriding the default settings
$.myObject.defaults.start = '3';
// no need to pass in options since it is now the default
$.myObject().publicMethod('Three');
// Attempting to access a private method will throw an error
$.myObject().privateMethod('Four');
});