Search code examples
javascriptjquerypluginsdefault

What is the difference between creating a jquery plugin with the default values as an extension of the plugin?


I'm confused as to how best create a JQuery plugin I'm working on.

The base layout I have is:

// Create Closure.
(function($) {

  // Plugin definition.
  $.fn.myPlugin = function(options) {

    var settings = $.extend(true, {}, $.fn.myPlugin.defaults, options);

    // Private:
    var privateVar = 'private';
    var privateFunction = function() {
      alert('hidden');
    }

    // Public:
    this.publicVar = 'public';
    this.publicFunction = function() {
      alert('visible');
    }

    return this;

  };

  // Plugin defaults – added as a property on our plugin function.
  $.fn.myPlugin.defaults = {
      foreground: "red",
      background: "yellow"
  };

// End Closure.
}(jQuery));

But I'm wondering why the JQuery docs (https://learn.jquery.com/plugins/advanced-plugin-concepts/), recommend having the defaults as a property, defined outside of the plugins body, as opposed to inside. So, the way I'm thinking it could be implemented instead is:

// Create Closure.
(function($) {

  // Plugin definition.
  $.fn.myPlugin = function(options) {

    // Plugin defaults – added as a property inside the plugin function.
    this.defaults = {
      foreground: "red",
      background: "yellow"
    };

    var settings = $.extend(true, {}, this.defaults, options);

    // Private:
    var privateVar = 'private';
    var privateFunction = function() {
      alert('hidden');
    }

    // Public:
    this.publicVar = 'public';
    this.publicFunction = function() {
      alert('visible');
    }

    return this;

  };

// End Closure.
}(jQuery));

Am I to assume that if the plugin is created in the second manner, then the defaults will be unable to be overridden? As the plugin object will first have to be instantiated?

If that's the case, then why does it really matter? As it's going to be instantiated at some point anyway...

Can anyone chime in with their view on this?


Solution

  • The first method creates one static version of the defaults, which are globally accessible (for overriding etc).

    The second creates one copy of the defaults per instance of the plugin and are only accessible on an instance of the plugin - therefore not overridable in any meaningful way.

    Opinion - javascript is apretty open language, you can implement things in any number of ways. When a library advises you to do something in a particular way its usually preferable to take the advice.