3
(function($) {
    $.fn.myFunction = function(config) {

        var defaults = {
            setting1: 'myDiv',
            setting2: ''
        };
        var config = $.extend(defaults, config); 

        //code here


    };

})(jQuery)


$(document).ready(function() {

    $.fn.myFunction({
        setting1: 'myDiv',
        setting2: ''
    });

});

This is how I've been using jQuery plugins, but I recently learned it should be used like:

$('#myDiv').myFunction({
    setting1: 'myDiv',
    setting2: ''
}); 

1) I take it this allows the usage of $(this) for $('#myDiv')?

2) Is $(document).ready(function() required?

3) Is there anything detrimental about the way I have been using this jQuery function?

4) If $('#myDiv').myFunction() is the proper usage, how would you call the function if it is simply a function to run at document ready - see my usage here: https://stackoverflow.com/a/12316349/1455709. Is this simply an incorrect usage of the function?

Community
  • 1
  • 1
Patrick
  • 3,490
  • 1
  • 37
  • 64
  • 2
    #1: Yes, jQuery modifies the value of `this` to refer to $('#myDiv') rather than myFunction as it would by default while executing myFunction. #2: `$(document).ready` is only required if you want your code to execute when the DOM is loaded. There is a [shorthand](http://stackoverflow.com/a/6004143/659910) though: `$(yourFunction)`. – Maros Sep 18 '12 at 07:31

2 Answers2

2
  1. Yes, as well as proper chaining if you return this from inside your function.

  2. Yes, if your code is run before the dom is loaded.

  3. It's not really jQuery, it doesn't work how people would expect it to. Somebody could call it as $('#myDiv').myFunction() and it wouldn't perform as expect.

  4. If you want a function that you can just run any time, don't add it to the jQuery prototype ($.fn). Instead you could add it onto $ like the other jQuery functions that don't require selectors, $.trim for example. Then you could call it like this: $.myFunction(options);

Richard Dalton
  • 35,513
  • 6
  • 73
  • 91
2

Calling $.fn.myFunction() and calling $('#myDiv').myFunction() are two different things. There is no right or wrong - it depends upon what you're doing.

Calling $.fn.myFunction()

This is essentially a static function and you can use it like that if you want. In the jQuery world, .fn is like .prototype so $.fn.myFunction() is like calling jQuery.prototype.myFunction(). It is allowed, but it's a static function call that is not associated with a specific jQuery object. If you just want a static function call, then you can do this, but this is not normally how the jQuery prototype is used and I would not generally recommend it. If you just want a static function and want to use the jQuery namespace, you can just do this:

$.myFunction = function(args) {/* your code here */};

and then call it like:

$.myFunction();

As there is no need to use the prototype at all.

Calling $('#myDiv').myFunction()

The prototype (e.g. .fn in the jQuery world is used when you want to add methods to actual jQuery objects.

When you do this $('#myDiv').myFunction() is a member function of a live jQuery object. You can refer to this inside the myFunction() implementation and it will be a jQuery object that, in this case holds the DOM object that corresponds to id="myDiv". If you return the jQuery object from your method, you can also use chaining.

Which to Use?

If your code operates on a jQuery object, then it should be a method on a live jQuery object and it should access this to get at the jQuery object instance data and you should declare it as $.fn.myFunction = function() {}; and call it as$('#myDiv').myFunction()`.

If you code does not operate on jQuery object and is just a utility function that you call and it doesn't always operate on a jQuery object, then, you should declare it as $.myFunction = function() {}; and you should call it as $.myFunction().

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Are there any advantages to using the jQuery namespace? How does this (`$.myFunction`) compare to the vanilla JavaScript methods of defining a function? Also from my understanding `(function($){})(jquery)` means the functions scope is hidden - should this wrapper still be used with `$.myFunction`? - updated original question with these. – Patrick Sep 18 '12 at 08:14
  • @Patrick - You do not want to introduce lots of top-level global functions because you risk conflicts with other code. jQuery is one existing namespace you can use that lets you define a globally accessible function without creating a new top-level global symbol. For a function that is not a jQuery method, there is no particular advantage to using the jQuery namespace. I don't. I create my own namespace and put all my globally accessible functions on my own namespace. This keeps my code less dependent upon jQuery (since I don't always use jQuery). – jfriend00 Sep 18 '12 at 08:26
  • is `(function($){})(jquery)` required around `$.myFunction = function(config){}`? – Patrick Sep 18 '12 at 08:52
  • `(function($){})(jquery)` is only required if you want to hide the use of the $ shortcut for jQuery. This is useful for plugins as there could be other libraries using that $ so [`jQuery.noConflict()`](http://api.jquery.com/jQuery.noConflict/) could have been run. – Richard Dalton Sep 18 '12 at 10:40
  • @Patrick - If you intend for other people to use your plug-in, then it is not safe to assume that `$` is `jQuery` so you can either surround your code with `(function($){})(jquery)` or code with `jQuery` instead of `$`. If it's just for use in your own projects where `$` is `jQuery`, then you don't need `(function($){})(jquery)`. – jfriend00 Sep 18 '12 at 21:04