Modify a variable inside a function

This question already has an answer here:

  • Is JavaScript a pass-by-reference or pass-by-value language? 29 answers

  • The modifyTest function is essentially creating a local, function-level variable called s ; that variable only exists within the scope of the function, so modifying it will not effect external scope.

    If you want to modify the external scope, you would not use an argument:

    var test = "This is a simple test";
    function modifyTest(){
        test = "modified test text";
    }
    console.log(test);   // This is a simple test
    modifyTest();
    console.log(test);   // Modified test text
    

    Not that you can modify an object passed by reference, so you can modify something's properties:

    var o = { test: 'This is a simple test' };
    function modifyTest(x){
        x.test = 'modified test text';
    }
    modifyTest(o);
    console.log(o.test);   // modified test text
    

    You could even pass in the name of the property you wish to modify:

    var o = { test: 'This is a simple test' };
    function modifyTest(x, name){
        x[name] = 'modified test text';
    }
    modifyTest(o, 'test');
    console.log(o.test);    // modified test text
    

    You're talking about calling a function "by reference". JavaScript (like most other functional languages) doesn't support that, as, changing a variable that is outside the current scope is a side-effect and those contradict functional programming paradigms.

    You can always change variables inside the current scope though. So any function defined within another function can change any local variable of the outer one.

    链接地址: http://www.djcxy.com/p/20804.html

    上一篇: swap()函数用于变量的值

    下一篇: 修改函数中的变量