将全局变量传递给函数

时间:2013-08-12 02:21:03

标签: javascript scope

为什么以下代码给我0而不是1?我希望我的函数更改在函数外声明的变量,但我不想在函数声明中指定变量。

that = 0;

function go(input) {
    input++;
}

go(that);

console.log(that);

5 个答案:

答案 0 :(得分:13)

正如Oriol所回答的那样,它不起作用,因为变量是按值传递的,所以你不会改变“那个”变量。解决方法是传递变量名称:

that = 0;

function test(input) {
    window[input]++;
}

test("that");

console.log(that); // 1

答案 1 :(得分:8)

那是因为你是按值传递变量,而不是通过引用。

在javascript中,所有变量都是按值传递的,除了通过引用传递的对象(实际上它们也是通过值传递但是它们是引用,见下文)。

你无法改变这种行为。

编辑:如果您不知道通过值/引用传递的内容,则应阅读教程。但是你有一些例子:

  • 按值传递的变量

    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
    
  • 传递的变量(值,但用作参考)

    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'
    

在你的情况下

你可以做到

  • 使你的变量成为一个对象的属性(在你的情况下,因为它是一个全局变量,使用window)并传递对象(引用),所以你可以改变它

    window.that = 0;
    function go(obj) {
        obj.that++;
    }
    go(window);
    console.log(that); // 1
    
  • 使用返回值

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

请注意,您无法执行

  • 将变量转换为对象

    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
    

    那是因为对象也是按值传递的,但它们是一个引用。这意味着在函数内部可以更改外部对象的属性(因为它是引用),但是您无法更改整个对象,因为它是按值传递的。

    请参阅此处的示例:https://stackoverflow.com/a/3638034/1529630

答案 2 :(得分:2)

这与指针,范围,通过引用传递变量以及所有爵士乐有关。

如果你真的想这样做,你可以在Javascript中传递一个对象:

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

我们所做的就是 一个对象,根据定义,它在Javascript中作为引用传递。然后我们确保正确修改对象的属性。

答案 3 :(得分:1)

您的代码

that = 0; //Global variable

function go(input) { //input is argument and is not passed by reference
    input++; //This just increments a local copy i.e 0
}

go(that); //Passed 0 

console.log(that);

而是这样做

that = 0;

function go() {
    that++;
}

go(); //Not passing any variable .. function can already see the gloabl "that" 

console.log(that); // This will print gloabl i.e. 1

答案 4 :(得分:-2)

实际上,您只需在函数内添加console.log(input),它就可以正常工作。

如果我错了,请纠正我。希望我能帮忙!

如果有人能解释为什么我错了,我会很高兴