Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would one write global code inside a function definition-call pair?

Tags:

javascript

I see examples where JavaScript code including jQuery and jslint use the notation below:

(function(){
  // do something
})();

instead of:

// do something

I first thought this is just for local scoping, i.e. creating local variables for the code block without polluting global namespace. But I've seen instances without any local variables at all too.

What am I missing here?

like image 375
Sedat Kapanoglu Avatar asked May 24 '10 15:05

Sedat Kapanoglu


People also ask

What surround the code inside a function?

All the code within the function is contained in the private scope of the function, meaning it can't be accessed at all from outside the function, making it truly private. The parenthesis are only required in this context because function in JavaScript can be both a statement or an expression, depending upon context.

How do you code a function?

To create a function, you write its return type (often void ), then its name, then its parameters inside () parentheses, and finally, inside { } curly brackets, write the code that should run when you call that function.

How do you define a function called name?

A function is defined by using the def keyword, followed by a name of your choosing, followed by a set of parentheses which hold any parameters the function will take (they can be empty), and ending with a colon. In this case, we'll define a function named hello() : hello.py. def hello():

When a variable is declared inside a function it is known as?

Local Variables Variables that are declared inside a function or block are local variables. They can be used only by statements that are inside that function or block of code.


1 Answers

It's about scope for functions, too - everything declared within the code block is scoped to that anonymous function only. Things are normally made public by the framework

(function($) {

  var localVarOnly = "local";

  $.fn.myCoolFunction = function() { // in the case of jquery, make this publicly available
    otherCoolFunction(); //alerts hi
    alert(localVarOnly); // alerts local
  };

  function otherCoolFunction() { // scoped to this anonymous function only
    alert('hi');
  };

})(jQuery);

otherCoolFunction(); // undefined
alert(localVarOnly); // undefined
like image 180
Dan Heberden Avatar answered Sep 22 '22 00:09

Dan Heberden