Home  >  Q&A  >  body text

How to assign global variables as parameters inside functions?

I want to directly use a global variable as a parameter of a function, and then assign a value to the parameter inside the function, instead of directly assigning a value to the global variable inside the function, so that it will not be hard-coded, but the test cannot assign a value.

s = 1;
a(s);
function a(m){
    e = m;
    b(e);
    function b(f){
        f = 2;
    }
}
alert(s);

The result is that s is still equal to 1. I know that s can be assigned a value directly in a function, but wouldn’t that be too hard to write? How can I assign a value of 2 to s in this way? It is convenient to pass different global variables for use later.

按键盘手指磨破皮按键盘手指磨破皮2627 days ago1982

reply all(2)I'll reply

  • Time丶Out

    Time丶Out2017-09-07 04:46:41

    JS object scope, take a closer look~

    reply
    0
  • 菜鸟-吉

    菜鸟-吉2017-09-04 08:24:51

    You don’t understand the connotation of function parameter passing: value passing, which means that S just gives 1 to function A and does not participate in it. In layman's terms: If you copy an S to a function, no matter how you operate it, it will not affect S itself.

    reply
    1
  • Cancelreply