Search code examples
javascriptjquerycoffeescriptanonymous-functionself-invoking-function

Why in javascript would an self-called anonymous function surround a jQuery onReady callback?


I am currently playing with playframework. I started out with the tutorial which uses Coffeescript. The CoffeeScript is converted to javascript, and this particular example, the javascript method needs to dynamically generate a list when the page is loaded.

The javascript generated uses a pattern that I've seen before, which I've read can be used for scoping variables or functions. That is, it envelopes everything inside an anonymous function.

However, within that anonymous function is the callback for window.isReady, in JQuery style.

(function() {
  $(function() {
      // the code within the callback goes here!
  });

}).call(this);

Is this just due to the result of this having been generated by a set of programmed rules, or could there be a reason to have the callback inside the anonymous function? A reason to scope that JQuery onReady callback?

Of course, the functionality works without being enclosed by the self-called anonymous function. So, is there any benefit?


Solution

  • Since the function delimits a scope, you want to do this as a best practice to prevent polluting the global namespace.

    In this simple example it might not be necessary since you don't save any variable, but you could have privates or other functions (and not have them global)

    Like this:

    (function() {
    
      var a = 5;
    
      var f = function() { ... }
    
    
      $(function() {
          // the code within the callback goes here!
          f();
          console.log(a);
      });
    
    }).call(this);