模块模式和闭包讨论

时间:2014-10-24 16:40:31

标签: javascript jquery design-patterns closures module-pattern

我的朋友最近开始在他的很多项目中使用JavaScript,尤其是模块模式。我问他是否可以帮助我理解他的工作经历: 他把这段代码放在一起解释模块模式和闭包,但他的代码似乎没有做任何事情......

 /* 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);
      }
     };
    })();

当他在团队视图会话中演示时,他开始以一种非常有趣的方式编写模块:他从命名空间对象开始,然后创建一个IIFE Shell函数返回一个对象,然后开始填充内部函数:

 /* 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 
     };

    })();

现在,JS大师可以解释一下为什么他写的代码没有做任何事情,如果他的例子是一个很好的闭包演示。

1 个答案:

答案 0 :(得分:1)

test.application = ( ... )();执行匿名javascript函数,该函数返回一个对象:

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

所以要运行它,你必须:

test.application.myapp();

关于一些闭包:

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() { ... }
}