網站搜尋

範圍 - JavaScript 中的私有函數


在一個基於 jQuery 的網頁應用程式中,我有各種腳本,其中可能會包含多個檔案,而我一次只使用其中的一個(我知道不包含所有檔案會更好,但我只負責 JS,所以那不是我的決定)。因此,我將每個檔案包裝在一個 initModule() 函數中,該函數註冊各種事件並進行一些初始化等操作。

現在我很好奇以下兩種定義函數而不污染全域命名空間的方法之間是否有任何差異:

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

答案#1

這兩種方法之間的主要差異在於函數何時可用。在第一種情況下,函數在宣告之後才可用,但在第二種情況下,它在整個作用域中都可用(這稱為提升)。

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

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

除此之外——它們基本上是相同的。

答案#2

這是一個幫助我管理 JavaScript 模組的範例:

base.js:

var mod = {};

mod.functions = (function(){

    var self = this;

    self.helper1 = function() {

    } ;

    self.helper2 = function() {

    } ;

    return self;

}).call({});

模組一.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({});