0

I came across a code like this:

function doSomething($, $variable){
  ...
}



(function ($){

  $(function () {
   doSomething ($, $('.div'));
  });

}(jQuery));

Is it the same as defining doSomething() inside of jQuery and removing the $?

Thanks

davexpression
  • 117
  • 1
  • 8
  • 1
    yes, it looks like some people overencapsulate stuff – smnbbrv Oct 04 '16 at 11:43
  • `$` is just like any other variable: you can pass it as function parameter or make it a global variable in the outer scope. – Álvaro González Oct 04 '16 at 11:43
  • you can refer to this post for clear understanding about it [link](http://stackoverflow.com/questions/10371539/why-define-an-anonymous-function-and-pass-it-jquery-as-the-argument). It explain quite well about the topic. – legend Oct 04 '16 at 11:43

2 Answers2

2

Is it the same as defining doSomething() inside of jQuery and removing the $?

If you mean, is it the same as:

(function ($){

  $(function () {
    function doSomething($, $variable){
    }
    doSomething($('.div'));
  });

}(jQuery));

...then no, because in the version in your question, doSomething is apparently global, whereas if you define it within another function, it isn't.

The structure at the end of your question is meant to protect against noConflict mode where $ does not equal jQuery, by creating a function and calling it, passing in jQuery and accepting it as an argument named $. It may be that the author was unaware of the fact that jQuery passes a reference to itself into the ready callback, so that code could more simply be:

function doSomething($, $variable){
  ...
}

jQuery(function($) {
   doSomething ($, $('.div'));
});
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

The first function is an IIFE that closes over $ and sets the value to jQuery. It's commonly used to avoid $ being overwritten by other code elsewhere.

Inside that IIFE, $ will always be jQuery, but outside the IIFE, it might not be.

The inner function $(function () {.. is just a DOM ready handler, that waits for the document to load before executing code inside it.

The doSomething function is defined outside the IIFE, and doesn't have access to the arguments from the IIFE, so $ could be undefined or something other than jQuery in that scope, hence the author decided to pass $ as an argument to doSomething($, $variable), it's a little hard to read because both the passed value, and the argument have the same name.

adeneo
  • 312,895
  • 29
  • 395
  • 388