I'm trying to better understand prototypes in JavaScript, so it made sense to me to make an object inside a jQuery function to make use prototype functions. As I understand it, this would be more memory efficient if making many objects (to avoid having duplicate variables and functions). So a simplified example:
(function($)
{
$.fn.gallery = function()
{
return this.each(function()
{
var gal = new Gallery($(this));
gallery.setup();
});
}
function Gallery($container)
{
this.$container = $container;
}
Gallery.prototype.setup = function()
{
//Code here
}
})(jQuery);
This makes sense to me, since for multiple calls of the function, there will only be one version of setup() method. But from the plugins that I've read, this isn't done. Is this a bad practice?
Judging from your code, there will only be one static setup method. Multiple Gallery
instances do exist though.
function Gallery(){}
Gallery.prototype.setup = function(){} //Adds a static method to Gallery
var gal = new Gallery(); //Creates a new Gallery instance
var gal2 = new Gallery(); //Creates a new Gallery instance
gal.setup == gal2.setup; //true