代码之家  ›  专栏  ›  技术社区  ›  ThiefMaster

JavaScript中的私有函数

  •  6
  • ThiefMaster  · 技术社区  · 14 年前

    在基于jQuery的web应用程序中,我有各种脚本,其中可能包含多个文件,我一次只使用其中一个(我知道不包括所有文件会更好,但我只负责JS,所以这不是我的决定)。所以我把每个文件包装成 init Module () 注册各种事件并进行初始化等的函数。

    现在,我想知道以下两种定义函数的方法是否有什么不同,它们没有扰乱全局命名空间:

    function initStuff(someArg) {
        var someVar = 123;
        var anotherVar = 456;
    
        var somePrivateFunc = function() {
            /* ... */
        }
    
        var anotherPrivateFunc = function() {
            /* ... */
        }
    
        /* do some stuff here */
    }
    

    function initStuff(someArg) {
        var someVar = 123;
        var anotherVar = 456;
    
        function somePrivateFunc() {
            /* ... */
        }
    
        function anotherPrivateFunc() {
            /* ... */
        }
    
        /* do some stuff here */
    }
    
    2 回复  |  直到 14 年前
        1
  •  8
  •   Andris    14 年前

    这两种方法的主要区别在于当函数可用时。在第一种情况下,函数在声明后变为可用,但在第二种情况下,它在整个范围内都可用(它被调用 起重 ).

    function init(){
        typeof privateFunc == "undefined";
        var privateFunc = function(){}
        typeof privateFunc == "function";
    }
    
    function init(){
        typeof privateFunc == "function";
        function privateFunc(){}
        typeof privateFunc == "function";
    }
    

    除此之外,他们基本上是一样的。

        2
  •  0
  •   andres descalzo    14 年前

    这是一个帮助我用javascript管理模块的模型:

    基.js:

    var mod = {};
    
    mod.functions = (function(){
    
        var self = this;
    
        self.helper1 = function() {
    
        } ;
    
        self.helper2 = function() {
    
        } ;
    
        return self;
    
    }).call({});
    

    模块1.js

    mod.module_one = (function(){
    
      var 
        //These variables keep the environment if you need to call another function
        self = this, //public (return)
        priv = {};   //private function
    
      priv.funA = function(){
      }
    
      self.somePrivateFunc = function(){
         priv.funA();
      };
    
      self.anotherPrivateFunc = function(){
    
      };
    
      // ini module
    
      self.ini = function(){
    
         self.somePrivateFunc();
         self.anotherPrivateFunc();
    
      };
    
      // ini/end DOM
    
      $(function() {
    
      });
    
      return self; // this is only if you need to call the module from the outside
                   // exmple: mod.module_one.somePrivateFunc(), or mod.module_one.ini()
    
    }).call({});
    
    推荐文章