Passing a global variable to a function

前端 未结 5 1729
被撕碎了的回忆
被撕碎了的回忆 2020-12-03 03:41

How come the following code is giving me a 0 instead of a 1? I want my function to change a variable declared outside the function but I do not want to specify the variable

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-03 04:07

    That's because you are passing the variable by value, not by reference.

    In javascript, all variables are passed by value, except objects, which are passed by reference (well, in fact they are passed by value too but they are a reference, see below).

    And you can't change that behaviour.

    Edit: If you don't know what passing by value/reference means, you should read a tutorial. But here you have some examples:

    • Variable passed by value

      function foo(bar){
         console.log(bar); // 1
         bar++;
         console.log(bar); // 2
      }
      var mybar = 1;
      console.log(mybar); // 1
      foo(mybar);
      console.log(mybar); // 1
      
    • Variable passed by (value but used as a) reference

      function foo(bar){
         console.log(bar.a); // 'b'
         bar.a = 'c';
         console.log(bar.a); // 'c'
      }
      var mybar = {a:'b'};
      console.log(mybar.a); // 'b'
      foo(mybar);
      console.log(mybar.a); // 'c'
      

    In your case

    You can do

    • Make your variable a property of an object (in your case, since it's a global variable, use window) and pass the object (reference), so you can alter it

      window.that = 0;
      function go(obj) {
          obj.that++;
      }
      go(window);
      console.log(that); // 1
      
    • Use a return value

      var that = 0;
      function go(input) {
          return input++;
      }
      that = go(that);
      console.log(that); // 1
      

    Note that you can't do

    • Convert your variable into an object

      var that = new Number(0); // Now it's an object number
      function go(input) {
          input++;
      }
      go(that);
      that *= 1; // Now it's a literal number
      console.log(that); // 0
      

      That's because objects are passed by value too, but they are a reference. That means that inside the function you can change the properties of the outer object (because it's a reference) but you can't change the entire object, because it's passed by value.

      See examples here: https://stackoverflow.com/a/3638034/1529630

提交回复
热议问题