How to declare a dynamic local variable in Javascript

前端 未结 7 2188
我在风中等你
我在风中等你 2021-02-04 08:37

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

7条回答
  •  失恋的感觉
    2021-02-04 09:10

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

    Global scope

    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
    

    Try it: 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)

    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
    

    Try it: http://jsfiddle.net/L4LbK/

    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.

    Function scope (using arguments)

    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);
    

    Try it: 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.

    Global scope as temporary

    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
    

    Try it: http://jsfiddle.net/X3p6k/3/

    Documentation

    • 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

提交回复
热议问题