javascript - setting global variables inside a function

后端 未结 3 993
悲&欢浪女
悲&欢浪女 2021-01-15 20:02

I am trying to create a function which will dynamically set the value of whatever global variable is passed as a parameter. It\'s not working, and I\'m trying to figure out

3条回答
  •  春和景丽
    2021-01-15 20:51

    Inside of functions are "variable environments". When the function setup is declared, and the parameter variable set, it creates a local variable in setup's variable environment for variable (the parameter).

    So that is why this assignment

    function setup(variable) {
     variable = 7;
    }
    

    Will never change the value sent to variable.

    Variables in JavaScript are values. As the variable is passed around, the only thing passed is the value of the variable. However, the value of the variable is assigned to the parameter (again poorly named in this example) variable. When the value of the parameter is assigned to 7, that only changes the local variable, and not the value of the passed variable.

    //the value of things is 5
    var things = 5;
    
    //the passed value 5 is assigned to variable
    function setup(variable) {
      //the value of variable is changed to 7 (and nothing is done with 5)
      variable = 7;
    }
    
    //the value of things is sent to setup
    setup(things);
    

    Hopefully this will be a little more enlightening. Consider a situation where setup was actually modifying the value of variable. A good example is when the value has state, such as an array or an object.

    //the value of things this time is an object
    var things = {};
    
    //the passed value of object is assigned to variable
    function setup(variable){
     //the value of variable (the object) has a property added named msg with a value of "hello world"
     variable.msg = "hello world";
    }
    
    //the value of things (an object) is sent to setup
    setup(things);
    alert(things.msg);//hello world
    

提交回复
热议问题