0

So I can't seem to find astraight answer on this, only vague examples of multiple variations where similar plugin/method declarations are used. I know that by saying

$.fn.myPlugin

I am defining a publicly available plugin method that can be executed on any valid jQuery object where the fn denotes the prototype. My question is then, by defining a method, either inside of my main plugin like so

$.fn.myPlugin.methodName

or outside of my plugin like so

$.something.methodName //where 'something' is in place of 'fn'

does this affect it being a public private/method? and if each is a different type of declaration, what is the difference.

The backstory of why I would like to know, to give some context to the situation, is that I want to define one main plugin that can be called and have run normally, however if the end user wants to redefine some method I have allowed to be public then they can do that. If I have any methods that I don't want the user to redefine but instead provide callbacks so they can hook into it, then I want to make that method private.

Mike
  • 632
  • 7
  • 22

1 Answers1

2

Anything set on $.whatever will be public, and therefore able to be modified by other developers.

If you want private methods, you should create a closure.

(function() {
    function init(jqObj) { ... } // do magic here
    $.fn.myPlugin = function() { init(this); } // avoid exposing core method
    $.fn.myPlugin.publicMethod = function() { ... }
    function privateMethod() { ... }
})();
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • ahhh okay, that makes sense. I do have closure being defined via `(function($) { }(jQuery));` I see now that private methods are just locally scoped functions. That is the piece I was missing, however, are you using the `function(init)` as a private function of the main plugin as to avoid anyone over writing the plugin itself? – Mike Sep 09 '16 at 14:14