Alex Djioev Alex Djioev - 17 days ago 4x
Javascript Question

Init function in javascript and how it works

I often see the following code:

(function () {
// init part

but I never could get my head around how it works. I find the last brackets especially confusing.
Could someone explain how it works in terms of Execution Contexts (EC) and Variable Objects (VO)?

ken ken

That pattern will create a new execution context (EC) in which any local variable objects (VO's) will live, and will likewise die when the EC exits. The only exception to this lifetime is for VO's which become part of a closure.

Please note that JavaScript has no magic "init" function. You might associate this pattern with such since most any self-respecting JS library (jQuery, YUI, etc.) will do this so that they don't pollute the global NS more than they need to.

A demonstration:

var x = 1; // global VO
    var x = 2; // local VO
x == 1; // global VO, unchanged by the local VO

The 2nd set of "brackets" (those are actually called parens, or a set of parentheses), are simply to invoke the function expression directly preceding it (as defined by the prior set of parenthesis).