JavaScript custom objects can be regarded as an alternative to the traditional jQuery plugin syntax. When you create a plugin, you bind all the logic of your plugin to a function where all your code will be executed. The function itself is, in turn, bound to the jQuery's prototype
property so that all the instances of jQuery elements (objects) share the same code and routines. Now imagine that you want to store all your logic elsewhere. This can be done with JavaScript custom objects. Let's see the details.
Let's start with a plain object:
var App = { test: function(element) { var question = confirm('Change the background color?'); if(question) { this.change(element); } else { return; } }, change: function(element) { $(element).css('background', 'yellow'); } };
To bind this custom object to the jQuery's prototypical chain and all of its objects, you have to use a syntax which is very familiar:
(function($) { $.fn.app = App; })(jQuery);
We've simply created an alias for our object that now behaves like a plugin. An example:
$(function() { $('#test').click(function() { $(this).app.test(this); }); });
this
points to the current jQuery element because it has been linked to the jQuery's fn
object. You can see a demo below.