Alex Djioev Alex Djioev - 1 year ago 145
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
Answer Source

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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download