簡體   English   中英

Javascript函數更改變量范圍

[英]Javascript function change variables scope

我試圖在匿名函數之外聲明一個函數,但仍然可以訪問所有匿名函數變量

下面是我正在談論的內容。

我只需要擺脫eval。

//Used to determine where the variable is being stored
var variableScope = "global";

(function(window){
        var variableScope = 'insideFunction',
        appearingToBeGlobalFunction = function(){
                alert("This Function appears Global but really isn't");
        };
        window["addFunction"]=function(funName,fun){
                //window[funName] = fun;  Doesn't work
                eval("window[funName]="+fun+";");
        }
})(window);

addFunction("alertTest",function(){
        alert(variableScope);
        appearingToBeGlobalFunction();
});

//should alert "insideFunction" and "This Function appears Global but really isn't"
alertTest();

編輯:這個問題的目標是最終使全局范圍從大量變量中保持清潔,但仍然具有訪問,設置和調用的便利,就好像它們是全局的一樣。 我已經得出結論,有一種方法可以做我想要的事情,但它需要在javascript中使用已棄用的功能。 這是一些示例代碼,顯示如何在沒有eval的情況下完成上述操作。 本文討論如何使用“with”。

var variableScope = "global";

var customScope = {
        variableScope : 'insideFunction',
        appearingToBeGlobalFunction : function(){
                alert("This Function appears Global but really isn't");
        }
};

function alertTest(){
        with(customScope){
             alert(variableScope);
             appearingToBeGlobalFunction();
        }
};

//should alert "insideFunction" and "This Function appears Global but really isn't"
alertTest();​
eval("window[funName]="+fun+";");

親愛的主啊。

這個“有效”的原因是你將函數funalertTest )轉換為字符串以將其放入eval參數中。

碰巧在大多數桌面瀏覽器中,本機JS函數的toString()結果將是一個看起來像函數表達式的字符串,其中包含與原始聲明相同的代碼。 您正在將函數轉換回字符串並在新的封閉函數的上下文中重新解析該字符串,因此新函數值是相同的代碼但具有不同的閉包。

但是, Function#toString像這樣工作, 在某些情況下它不會 依靠函數分解是不安全的; 避免。

你當然只能使用eval做這種可怕的hackery,盡管沒有理由window[funName]= part必須在eval window[funName]= eval('('+fun+')'); 會很好地工作(嚴重)。

我試圖在匿名函數之外聲明一個函數,但仍然可以訪問所有匿名函數變量

為什么你會做那樣瘋狂的事情?

你無法擺脫eval,仍然希望它能夠發揮作用。 這是在關閉范圍之后查看范圍成員的唯一方法。 我過去曾經搞過類似的東西,但實際上我從未在任何地方使用它。 考慮一個替代解決方案,無論你想要完成什么。

你可以強制變量在全局范圍內,例如代替var variableScope = 'insideFunction'你使用window.variableScope = 'insideFunction'

這個問題的目標是最終保持全球范圍內的大量變量,但仍然具有訪問,設置和調用的便利,就好像它們是全局的一樣。 我已經得出結論,有一種方法可以做我想要的事情,但它需要在javascript中使用已棄用的功能。 這是一些示例代碼,顯示如何在沒有eval的情況下完成上述操作。 本文討論如何使用“with”。

var variableScope = "global";

var customScope = {
        variableScope : 'insideFunction',
        appearingToBeGlobalFunction : function(){
                alert("This Function appears Global but really isn't");
        }
};

function alertTest(){
        with(customScope){
             alert(variableScope);
             appearingToBeGlobalFunction();
        }
};

//should alert "insideFunction" and "This Function appears Global but really isn't"
alertTest();​

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM