2013-10-06 81 views
0

我想寫一個叫做App的主函數。 它具有一定的公共和私人功能。請參閱下面的代碼。 我希望它以模塊化的方式寫它。jquery寫模塊功能

問題是我想映射一些私人功能公共職能,我無法做到這一點。

例如;

我想打電話App.ModuleA這應該調用_A()私人功能,並讓我訪問其公共職能,如App.ModuleA.fun_1

我知道讓它工作;我需要將_A()公開。但是,是否可以映射函數?

我該如何實現這樣的映射?任何人都可以建議更好的編碼結構所以我可以訪問應用程序內部的子功能和他們的公共職能嗎?

現在我得到錯誤TypeError: _A is not a function當我打電話App.ModulaA();

var App = function() { 
     // App Private Functions 
     var _A = function() { 
      return { 
       fun_1: function() { 
        alert("_A.fun_1"); 
       }, 
       fun2: function() { 
        alert("_A.fun2"); 
       } 
      }; 
     }(); 
     // App Public Functions 
     return { 
      init: function() { 
       alert("App.init"); 
      }, 
      ModulaA: function() { 
       return _A(); // doesnot work 
       // return this._A(); // doesnot work     
      } 
     }; 
    }(); 

App.ModulaA(); 

回答

2

_A()沒有自我調用函數,從而去掉括號,看到它在行動here

}() <---- remove parenthesis 
+0

你能解釋一下'''}()'''這個目的是什麼?什麼是自我調用?它如何在App定義中有用,但不在子函數_a中? – django

+0

那些括號立即執行該函數,讓事情DRY看到這個[鏈接](http://peter.michaux.ca/articles/an-important-pair-of-parens)的解釋。 – Max

1

你需要做的一個變化:

var _A = function() { 
    //... 
}(); 

// change to: 
var _A = function() { 
    //... 
}; 

或者:

return _A(); 
// change to: 
return _A; 

在你的榜樣_A已經被評估過,因此不再是函數。

1
var App = function() { 
    //App Private Functions 
    var _A = function() { 
     return { 
      fun_1: function() { 
       alert("_A.fun_1"); 
      }, 
      fun2: function() { 
       alert("_A.fun2"); 
      } 
     }; 
    }, 
    init = function() { 
     alert("App.init"); 
    }, 
    ModulaA = function() { 
     return _A(); 
    }; 

    // App Public Functions 
    return { 
     init: init, 
     ModulaA: ModulaA 
    }; 
}(); 

var moduleA = App.ModulaA(); 
moduleA.fun_1(); //Works 
moduleA.fun2(); //Works