Passing a global variable to a function

前端 未结 5 1734
被撕碎了的回忆
被撕碎了的回忆 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:32

    This has to do with pointers, scope, passing variables by reference, and all that jazz.

    If you really want to do this, you can pass an object in Javascript like this:

    var that = {value: 0};
    function go(input) {
        input.value++;
    }
    go(that);
    console.log(that.value);
    

    All we've done is made that an object which is by definition passed as a reference in Javascript. Then we just make sure we properly modify the object's attributes.

提交回复
热议问题