Turk Turk - 1 month ago 4
Javascript Question

$.fn.myPlugin vs $.something.myPlugin in regard to private and public methods

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


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


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.


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() { ... }