Search code examples
jqueryobjectfunction-prototypes

Should you be creating an object in a jQuery wrapper, or is it bad practice? (example inside)


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?


Solution

  • 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
    


    If you want to learn JavaScript, I recommend to not start with JQuery. When you've mastered JQuery, you have hardly learned anything about JavaScript. When you start with JavaScript, however, learning JQuery is pretty easy.