Not sure what you mean "inline" or by "scope the vars inside";
variables declared inside the function are scoped "inside" (they have
lexical scope to the function), as long as they are preceded with the
var declaration (if not, they are global, even with this format).

The closing/end parens creates a self-invoking, anonymous function.
The function is called immediately and returns whatever is inside;
sometimes you'll see jQuery called this way:

(function($){

  /* this variable is only available within the function, unless you
create a closure */
  var foo1 = 'bar';

 /* this variable has global scope and can be accessed later */
  foo2 = 'boo';

})(jQuery);

In this case, it's anonymous (the function has no name and isn't
assigned to a var), and self-invoking (the parens at the end invoke
the function as in T.J. Crowder's f() example), and it additionally is
passing an argument to the function (the jQuery object--which is
global, which is then assigned to the $ inside the function). The foo#
variables inside have different scope as indicated. A variable
declared inside a function with var can still be accessed outside the
function by means of a closure.

On Mar 15, 6:35 am, "T.J. Crowder" <t...@crowdersoftware.com> wrote:
> Hi,
>
> On Mar 15, 12:55 pm, lovespring <iamd...@gmail.com> wrote:
>
> > (function(){})();
> > does it conform to the grammar?
>
> Yes, it does.  That line defines a function inline:
>
>     (function(){})
>
> ...and then calls it immediately using () like any other function:
>
>     (function(){})();
>
> (You need the parens around the definition so the () gets applied to
> the right expression.)
>
> Other than the obvious fact I'm using a symbol 'f' here, it's
> identical to:
>
>     var f = function(){};
>     f();
>
> That sort of thing is frequently used to scope the vars inside rather
> than having them populate the containing scope.
>
> HTH,
> --
> T.J. Crowder
> tj / crowder software / com
> Independent Software Engineer, consulting services available

Reply via email to