2013-06-26 25 views
0
function exampleFunction(){ 
    var theVariable = "Lol!"; 
    var variable2 = Lol.toLowerCase(); 
    console.log(theVariable); 
    delete theVariable; //to prevent bugs, I want to ensure that this variable is never used from this point onward. 
    console.log(theVariable); //This still prints "Lol!", even though I just tried to delete the variable. 
} 

在JavaScript中,是否可以防止某個變量在某個點後被用於某個函數?我試過聲明一個名爲theVariable的字符串,然後我嘗試使用delete theVariable刪除該變量,但console.log(theVariable)仍然會打印theVariable的值,即使在該點之後。如何防止變量在某個點之後被使用?

我嘗試使用delete theVariable使theVariable不可用,從那時起(爲了防止我不再需要使用該變量時不小心使用該變量),但似乎沒有這種效果。有什麼辦法可以解決這個限制嗎?

+0

反正你不能在函數外面使用它,所以當函數返回時var就不見了。您可以將其設置爲未定義,但詞彙名稱將始終從功能的詞法範圍中劃分出來。 – dandavis

+0

@dandavis「it」指的是什麼? –

+0

theVariable = undefined;儘可能接近你想要的東西。 – dandavis

回答

5

一種方法是限制其範圍。由於JavaScript沒有塊範圍,這需要一個IIFE(或類似技術):

function exampleFunction(){ 
    var variable2; 
    (function() { 
     var theVariable = "Lol!"; 
     variable2 = Lol.toLowerCase(); 
     console.log(theVariable); 
    })(); 
    // theVariable is now out of scope, and cannot be referenced 
} 
2

在這種情況下,你可以設置像theVariable = undefined

價值undefineddelete功能不起作用如你預期

從文檔

delete運算符從對象中刪除一個屬性。

在這種情況下,theVariable不是對象的屬性,它是當前函數作用域中的一個變量。

+2

輝煌的研究... – dandavis

+0

您引用的句子有點誤導人,因爲將'delete'應用於變量是合法的,其確切行爲取決於變量是局部還是全局的,是否在' eval'與否,以及JS解釋器運行的代碼(例如,瀏覽器或瀏覽器版本)。 – ruakh

+0

不幸的是,這不會阻止變量被設置爲非未定義的值 - 我更喜歡[ruakh的解決方案](http://stackoverflow.com/a/17311333/975097)。 –

0

您不能刪除原始類型,只是對象。如果您不想在某個點後使用某個變量,只需查看您的代碼,以免使用它。不幸的是,JS沒有限制範圍限制變量的可見性。你必須手動檢查。

或者,將值設置爲undefined。

相關問題