我試圖聲明函數匿名函數之外,但仍然有接取到所有的匿名函數變量JavaScript函數改變變量的作用域
下面是展示我在說什麼。
我只是需要擺脫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的情況下完成上述操作。 This article討論如何使用「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();
你有一個局部變量名爲「appearingToBeGlobalFunction」......這是一個悖論。你爲什麼認爲分配給該局部變量的函數應該是全局的?它是本地的。 – 2010-09-11 16:39:06
@ŠimeVidas:他沒有使用'var'來定義該變量,因此它在全局上下文中定義。它應該被重命名爲'appearingToBeGlobalFunctionAndActuallyIs'。 – 2010-09-11 16:49:46
是的,他做到了。 「variableScope」和「出現......」都是局部變量。 (注意它們之間的逗號分隔符)。 http://stackoverflow.com/questions/694102/declaring-multiple-variables-in-javascript – 2010-09-11 16:58:25