2012-05-12 25 views
0

有沒有辦法在JavaScript中創建私有全局變量?我試圖環顧四周,而且我一直在討論施工人員 - 這看起來不太全球化。在javascript中製作全局私有變量的方法?

感謝

+7

你是什麼意思的「私人全球變量」?你能提供一個例子嗎? –

+2

這就像是說「全局變量不是全局的」? – Joseph

+0

你可能想閱讀有關即時函數:http://stackoverflow.com/questions/8475578/what-is-the-reason-for-this-javascript-immediate-invocation-pattern –

回答

2

不確定你的用例是什麼。我假設你有一個包含一些函數和變量的js腳本文件,並且你想在全局中公開其中的一部分,但其餘部分保留爲腳本文件的私有文件。你可以用閉包來實現這一點。基本上你創建了一個你立即執行的函數。在函數內部放置原始代碼。然後將所需的功能導出到全局範圍中。

// Define a function, evaluate it inside of parenthesis 
// and execute immediately. 
(function(export) { 

    var myPrivateVariable = 10; 

    function myPrivateFunction(param) { 
    return param + myPrivateVariable; 
    } 

    export.myGlobalFunction = function(someNumber) { 
     return myPrivateFunction(someNumber); 
    }; 
})(this); // The *this* keyword points to *window* which 
      // is *the* global scope (global object) in a web browser 
      // Here it is a parameter - the *export* variable inside the function. 

// This is executed in the global scope 
myGlobalFunction(2); // yields 12 (i.e. 2 + 10) 
myPrivateVariable; // Error, doesn't exist in the global scope 
myPrivateFunction(2) // Error, doesn't exist in the global scope 
1

要回答你的問題,不,因爲有在JavaScript中沒有訪問修飾符是不可能的。任何函數都可以訪問在全局範圍內聲明的變量。

正如在本答案的評論中指出的那樣,您可以創建具有私人成員的對象。 Crockford在private members in Javascript上有一個頁面。他用下面的代碼來說明他的觀點:

function Container(param) { 

    // private method 
    function dec() { 
     if (secret > 0) { 
      secret -= 1; 
      return true; 
     } else { 
      return false; 
     } 
    } 

    this.member = param; 
    var secret = 3; 
    var that = this; 

    // privileged method 
    this.service = function() { 
     return dec() ? that.member : null; 
    }; 
} 

在上面的例子中,PARAM,祕密,這都是私人的,因爲它們不能從外部訪問。更清楚的是,這些變量只能通過特權或私有方法訪問,區別在於可以從對象的任何實例調用特權方法。正如評論中所建議的那樣,這可以通過使用閉包來實現。

引用克羅克福德快速解釋關閉,但你可以找到大量related questions

這意味着,一個內部函數總是可以訪問 VAR和它的外部函數的參數,外 函數返回後還是一樣。

+1

......不同之處在於你可以創建基本上[通過閉包]的變量(http://phrogz.net/js/Classes/OOPinJS.html)。 – Phrogz

+1

@Progro您當然可以這樣做,但您不能讓包含私有值的實際變量位於全局範圍內。 – Radu

+0

正確;我只對你原來的答案的第一句話發表評論。 :) – Phrogz