What is the reason for this javascript instant call pattern?

I looked at the following template while viewing the SlickGrid source code:

(function ($) {
  var SlickEditor = {

    TextCellEditor: function (args) {
      ...
    },

    LongTextCellEditor: function (args) {
      ...
    }
  };

  $.extend(window, SlickEditor);

})(jQuery);

If I understand this correctly, it uses a direct call to define various function objects, and then combine them into a global namespace.

So, I could just define my functions globally, like this, and it will have the same effect, right?

function TextCellEditor (args) {
  ...
}

function LongTextCellEditor (args) {
  ...
}

The only difference I see is that in the first version I can use shorthand $to refer to an object jQuery. In addition, the result will be the same in both cases.

I would like to know if I missed something. Maybe there is another good reason for this?

. : , , . , . , - .

, , . , $ TextCellEditor(). $ TextCellEditor(), .

.

+5
4

, , , .

self invoking javascript, : http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth

javascript: http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting

jQuery vairable in 2 :

1: $, , , $ -

2: -

:

var public_and_global=true;

(function(){
  var private_and_local = true;

  function local_func() {
   //can use private_and_local as well as public_and_global
  }

})();

function global_func() {
   //can only use public_and_global
}
+3

IIFE.

, , .

" ", IIFE.

+1

, . , , , , . , , :

var UID = (new Date).getTime();
$.uniqueID = function() { return (UID++).toString(16); }

, UID , , script, . , $, .

, , .

0

, . :

, , , ?

. . , jQuery. .

Despite the fact that the fragment you showed does not demonstrate this, you can define some private data, in addition to functions within this area, for example, fixed rows or lookup tables or any auxiliary data that these methods may require, and the functions will have access to this data, and yet this data will not be available for any other code (similar to "private" in OO), and this data will not pollute the global namespace.

0
source

All Articles