Athapali
Athapali

Reputation: 1089

module pattern and closure discussion

My friend has recently started working with JavaScript in a lot of his projects, especially the module pattern. I asked him if he can help me understand closure from his work experience: He put together this piece of code to explain both module pattern and closure but his code doesn't seem to do anything..

 /* Write JavaScript here */
    var test = test || {};

    test.application = (function(){

     function closure(){
      var a = {
       name : 'Reena',
       age : 32,
       doSomeThing: function(){
        alert(this.name);
        alert(this.age);
       }  
      };
      return a;
     }


     return { 
      myapp: function(){
       var myClosure = closure();
       var a = myClosure.doSomeThing();
       var myname =myClosure.name;
        alert("myname: " + myname);
      }
     };
    })();

When he was demoing this over a teamview session, he started wrting the module in a very interesting way: He started out with the namespace object and then created an IIFE Shell function returning an object and then started filling out the inner functions:

 /* Write JavaScript here */
    var test = test || {};

    test.application = (function(){

        function closure(){    
         //then he worked on this ..
        }
     return {       
       //then he worked on the return value for the IIFE which is another javascript function 
     };

    })();

Now, can JS gurus explain me why the piece of code he wrote is not doing anything and if his example is a good demo for closure.

Upvotes: 0

Views: 90

Answers (1)

Johan Karlsson
Johan Karlsson

Reputation: 6476

test.application = ( ... )(); executes an anonymous javascript function, which returns an object:

{
    myapp: function(){ ... }
}

So to run it you have to:

test.application.myapp();

Regarding some closures:

myapp(){
    this              => { myapp: function(){ ...} }
    myapp             => function(){ ... }
    closure           => function(){ ... }
    name              => undefined
    age               => undefined
    doSomething       => undefined
}

closure().myapp       => undefined
closure().closure     => undefined
closure().name        => "Reena"
closure().age         => 32
closure().doSomething => function(){ ... }

doSomeThing(){
    myapp             => undefined
    closure           => function(){ ... }
    name              => undefined
    age               => undefined
    doSomeThing       => undefined
    this              => { name: 'Reeva', age: 32, doSomeThing: function() { ... }
}

Upvotes: 1

Related Questions