Mike
Mike

Reputation: 637

$.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

$.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.

Upvotes: 0

Views: 85

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324750

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

Upvotes: 2

Related Questions