Javascript函数更改变量范围 [英] Javascript function change variables scope

查看:64
本文介绍了Javascript函数更改变量范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在匿名函数之外声明一个函数,但仍然可以访问所有匿名函数变量

I am attempting to declare a function outside of anonymous function but still have acess to all of the anonymous functions variables

下面是演示我正在谈论的内容。

Below is demonstrating what I'm talking about.

我只需摆脱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 。

The goal of this question was to ultimately keep the global scope clean from tons of variables, but still have the convenience of accessing, set and calling as if they were global. I have concluded there is a way to doing what I'm after but it requires a deprecated functionality in javascript. Here is some example code showing how to accomplish the above without eval. This article discusses how to use "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,仍然期望它能够发挥作用。这是在关闭范围之后查看范围成员的唯一方法。我搞砸了一些东西类似过去,但我永远不会在任何地方使用它。考虑一个替代解决方案,无论你想要完成什么。

You can't get rid of eval and still expect it to work. That's the only way to take a look at members of the scope after it's been "closed." I've messed around with something similar in the past, but I would never actually use it anywhere. Consider an alternate solution to whatever you're trying to accomplish.

这篇关于Javascript函数更改变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆