« Yield! | Main | F3 - Open Definition »
Friday
Mar252011

Anonymous packages

Version 1.8 adds (among other things) support for anonymous packages. Variables declared inside an anonymous package is only visible inside the same package block.

    var x = "hello";
    package {
        var x = 17;
        console.log(x); // writes 17
    }
    console.log(x); // writes "hello"

Anonymous packages are useful for ensuring that a block of code doesn't pollute the global namespace. If you have several anonymous packages, they are also hidden for each other.

Behind the scenes, anonymous packages are transformed into this pattern:

   (function(){
       ...
   })();

PrintView Printer Friendly Version

EmailEmail Article to Friend