【问题标题】:module pattern and closure discussion模块模式和闭包讨论
【发布时间】:2014-10-24 16:40:30
【问题描述】:

我的朋友最近开始在他的很多项目中使用 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);
      }
     };
    })();

当他在 teamview 会话中演示这个时,他开始以一种非常有趣的方式编写模块:他从命名空间对象开始,然后创建一个返回对象的 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 大师能否解释一下为什么他编写的代码没有做任何事情,以及他的示例是否是一个很好的闭包演示。

【问题讨论】:

  • 运行测试使用:test.application.myapp();
  • 不应该自动执行吗?

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


【解决方案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() { ... }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    相关资源
    最近更新 更多