2

I have the following code:

(function ($) {
    /**
    * Opens a new modal window
    * @param object options an object with any of the following options
    * @return object the jQuery object of the new window
    */
    $.modal = function (options) {
        var settings = $.extend({}, $.modal.defaults, options),
            root = getModalDiv(),

Can someone explain why the function is given to the object $.modal and not just modal? Also what's the significance of the first line:

2 Answers2

7

Because it is a jQuery plugin, they're defining it to run withing the jQuery namespace of $.

zzzzBov
  • 174,988
  • 54
  • 320
  • 367
user229044
  • 232,980
  • 40
  • 330
  • 338
0

Since it's in a closure ((function(){})()) code outside of it couldn't access modal. Alternatively you could do it like this:

var holder = {};

(function($){
    holder.modal = function()
    };
})();

holder.modal();
Community
  • 1
  • 1
Thomas
  • 8,426
  • 1
  • 25
  • 49
  • 1
    Sure you can -- `modal = function(){}`. Without `var`, `modal` would be available globally. – josh3736 Aug 24 '12 at 14:03
  • This does not have anything to do with closures. Local variables cannot be accessed from outside a function because they are that: **local**, whether the function is a closure or not. `(function(){})()` is an *immediately executed function expression* and you are right, the function itself is a closure, but so is every user-defined function. – Felix Kling Aug 24 '12 at 14:04
  • To expand on josh3736's comment, if you simply typed `modal = function () { }`, this is identical to typing `window.model = function () { }`, and it would be available globally. Variables declared without `var` are implicitly attached to the `window` object (or whichever global context your JS environment is executing in). As Felix said, the question really has nothing to do with closures and everything to do with binding a jQuery plugin to the jQuery object instead of the global object. – user229044 Aug 25 '12 at 14:57