我试图声明函数匿名函数之外,但仍然有接取到所有的匿名函数变量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