如何在Javascript中声明动态局部变量 [英] How to declare a dynamic local variable in Javascript

查看:103
本文介绍了如何在Javascript中声明动态局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想动态创建一个局部变量。 JavaScript:动态创建循环变量并不是我想要的。我不想要一个阵列。我想像本地变量一样访问它。

I want to create a local variable dynamically. JavaScript: Dynamically Creating Variables for Loops is not exactly what I am looking for. I dont want an array. I want to access it like a local variable.

类似于:

    <script type="text/javascript">
        var properties = new Object();
        properties["var1"] = "value1";
        properties["var2"] = "value2";

        createVariables(properties);

        function createVariables(properties)
        {
            // This function should somehow create variables in the calling function. Is there a way to do that?
        }
        document.write("Outside the function : " + var1 + "<br>");
        document.write("Outside the function : " + var2 + "<br>");
    </script>

我尝试了以下代码。

    <script type="text/javascript">
        var properties = new Object();
        properties["var1"] = "value1";
        properties["var2"] = "value2";

        createVariables(properties);

        function createVariables(properties)
        {
            for( var variable in properties)
            {
                try
                {
                    eval(variable);
                    eval(variable + " = " + properties[variable] + ";");
                }
                catch(e)
                {
                    eval("var " + variable + " = '" + properties[variable] + "';");
                }
            }
            document.write("Inside the function : " + var1 + "<br>");
            document.write("Inside the function : " + var2 + "<br>");
        }
        document.write("Outside the function : " + var1 + "<br>");
        document.write("Outside the function : " + var2 + "<br>");
    </script>

但是在createVariables()之外无法访问生成的变量。

But the generated variables are not accessible outside the createVariables().

现在,我有这个解决方案。

Now, I have this solution.

    <script type="text/javascript">
        var properties = new Object();
        properties["var1"] = "value1";
        properties["var2"] = "value2";

        function createVariables(properties)
        {
            var str = "";
            for( var variable in properties)
            {
                str += "try{";
                str += "eval('" + variable + "');";
                str += "eval(\"" + variable + " = properties['" + variable + "'];\");";
                str += "}";
                str += "catch(e){";
                str += "eval(\"var " + variable + " = properties['" + variable + "'];\");";
                str += "}";
            }
            return str;
        }

        eval(createVariables(properties));
        document.write("Outside the function : " + var1 + "<br>");
        document.write("Outside the function : " + var2 + "<br>");
    </script>

这是有效的。但我正在寻找替代/更好的解决方案。是否可以在没有评估的情况下进行?

This works. But I am looking for an alternative/better solution. Is it possible to do it without eval?

编辑:04年7月

我尝试了类似于@Jonathan建议的解决方案。

I tried a solution similar to what @Jonathan suggested.

    <script type="text/javascript">

    var startFunc = function(){
        var self = this;

        self.innerFunc = function innerFunc(){
            var properties = new Object();
            properties["var1"] = "value1";
            properties["var2"] = "value2";
            properties["var3"] = "value3";

            function createVariables(caller, props) {
                 for(i in props) { 
                     caller[i] = props[i];
                 }  
                 caller.func1();
            }
            createVariables(self, properties);
            console.log( var1 );
        }

        self.func1 = function func1(){
            console.log( "In func 1" );
            console.log( var2 );
        }

        innerFunc();
        console.log( var3 );
    }

    startFunc();


    </script>

一切正常。但它实际上是创建全局变量而不是在函数中创建变量。

This all works fine. But it is actually creating global variables instead of creating the variables in the function.

传递给createVariables()函数的self是窗口。我不确定为什么会这样。我正在为自己分配功能范围。我不确定这里发生了什么。无论如何,在这种情况下创建全局变量。

The "self" passed to the createVariables() function is window. I am not sure why it is happening. I am assigning the function scope to the self. I am not sure what is happening here. It is anyway creating global variables in this case.

如果我的问题不明确,

我是什么之后在调用者中创建局部变量。场景就像

What I am after is creating local variables in the caller. The scenario is like

1)我在一个函数中。

2)我调用另一个函数,它返回一个地图[此地图包含变量的名称和值]。

3)我想动态创建所有变量,如果它们尚未定义。如果已经定义了[global / local],我想更新它们。

4)创建这些变量后,我应该能够在没有任何上下文的情况下访问它们。[只是变量名称]

1) I am inside a function.
2) I invoke another function which returns me a map[This map contains name and value of a variable].
3) I want to dynamically create all the variables, if they are not already defined. If they are already defined [global/local], I want to update them.
4) Once these variables are created, I should be able to access them without any context.[Just the variable name]

    <script type="text/javascript">
        function mainFunc()
        {
            var varibalesToBeCreated = getVariables();
            createVariables(varibalesToBeCreated);

            alert(var1);
            alert(var2);
        }

        function createVariables(varibalesToBeCreated)
        {
            // How can I implement this function, 
            // such that the variables are created in the caller? 
            // I don't want these variables this function.
        }

        function getVariables()
        {
            var properties = new Object();
            properties["var1"] = "value1";
            properties["var2"] = "value2";  
        }


        mainFunc();
    </script>


推荐答案

根据你想要的变量范围而定有,这可以通过几种不同的方式实现。

Depending on the scope you'd like the variables to have, this could be accomplished in a few different ways.

全球范围

要将变量放在全局范围内,您可以使用窗口[varName]

To place the variables in the global scope, you could use window[varName]:

function createVariables(variables) {
    for (var varName in variables) {
        window[varName ] = variables[varName ];
    }
}

createVariables({
    'foo':'bar'
});
console.log(foo); // output: bar

试一试: http://jsfiddle.net/nLt5r/

请注意,全球范围是一个肮脏的公共场所。任何脚本都可以读取,写入或删除此范围内的变量。由于这个事实,你冒着破坏使用与你的变量名相同的不同脚本的风险,或者破坏你的另一个脚本。

Be advised, the global scope is a dirty, public place. Any script may read, write, or delete variables in this scope. Because of this fact, you run the risk of breaking a different script that uses the same variable names as yours, or another script breaking yours.

功能范围(使用

Function scope (using this)

在函数范围内创建变量( this .varName ),你可以使用 bind

To create variables in a function's scope (this.varName), you can use bind:

var variables = {
    'foo':'bar'
};
var func = function () {
    console.log(this.foo);
};
var boundFunc = func.bind(variables);
boundFunc(); // output: bar

试一试: http://jsfiddle.net/L4LbK/

根据您对绑定函数引用的处理方式,此方法稍微容易受到影响外部修改变量。任何可以访问 boundFunc 的东西都可以通过使用 boundFunc.varName ='new value'来改变或引用值的值; 这可能对您有利,具体取决于用例。

Depending on what you do with the bound function reference, this method is slightly vulnerable to outside modification of the variables. Anything that can access boundFunc can change or refer to the value of the values by using boundFunc.varName = 'new value'; This may be to your advantage, depending on use case.

功能范围(使用参数)

您可以使用 apply 将值数组作为参数传递:

You can use apply to pass an array of values as arguments:

var variables = [
    'bar'
];
var func = function (foo) {
    console.log('foo=', foo);
};
func.apply(null, variables);

试一试: http ://jsfiddle.net/LKNqd/

由于参数本质上是短暂的,因此除了外部之外没有任何东西可以干扰或引用这些值,除了通过修改变量数组并重新调用该函数。

As arguments are ephemeral in nature, nothing "outside" could interfere with or refer back to the values, except by modifying the variable array and re-calling the function.

全局范围为临时

这是一个小实用程序函数,它将临时使用全局范围。此函数对使用全局范围的代码也很危险 - 这可能会破坏其他脚本创建的变量,使用风险由您自己承担:

And here's a small utility function that will make temporary use of the global scope. This function is dangerous to code that also uses the global scope -- this could blast over variables that other scripts have created, use at your own risk:

var withVariables = function(func, vars) {
   for (var v in vars){
       this[v] = vars[v];
   }
   func();
   for (var v in vars){
       delete this[v];
   }
};

// using an anonymous function
withVariables(
    function () {
        console.log('anonymous: ', foo);   
    },
    {
        'foo':'bar'   
    }
); // output: bar

// using a function reference
var myFunction =function () {
    console.log('myFunction: ', foo);   
};
withVariables(myFunction, {
    'foo':'bar'   
}); // output: bar

console.log(foo); // output: undefined

试一试: http://jsfiddle.net/X3p6k/3/

文档

  • bind on MDN - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
  • apply on MDN - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
  • window on MDN - https://developer.mozilla.org/en-US/docs/Web/API/Window

这篇关于如何在Javascript中声明动态局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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