Magic
Magic

Reputation: 1196

Alter outer argument var of node.js

Please look at these 3 code blocks first.

Code Block 1:

var t1 = function(aaa) {
        setTimeout(function(){
        a = 'bb';
        aaa.push(a);
    }, 1000);

}

var t3 = function() {
    var aa = new Array;
    aa[0] = 'aa';

    console.log(aa);
    t1(aa);

    setTimeout(function(){
        console.log(aa);
    }, 3000);
}

t3();

Output: [ 'aa' ] [ 'aa', 'bb' ]


Code Block 2:

var t1 = function(aaa) {
        setTimeout(function(){
        aaa[1] = 'bb';
    }, 1000);

}

var t3 = function() {
    var aa = new Array;
    aa[0] = 'aa';

    console.log(aa);
    t1(aa);

    setTimeout(function(){
        console.log(aa);
    }, 3000);
}

t3();

Output: [ 'aa' ] [ 'aa', 'bb' ]


Code Block 3:

var t1 = function(aaa) {
        setTimeout(function(){
        aaa = aaa.concat('bb');
    }, 1000);

}

var t3 = function() {
    var aa = new Array;
    aa[0] = 'aa';

    console.log(aa);
    t1(aa);

    setTimeout(function(){
        console.log(aa);
    }, 3000);
}

t3();

Output: [ 'aa' ] [ 'aa' ]


The problem is code block 3 that the 'concat' method can't modify the 'aaa' var pass by argument.
What's the difference of 'concat' ,'push' and direct modify?

Upvotes: 0

Views: 75

Answers (1)

qiao
qiao

Reputation: 18229

In codeblock 1 and 2, you are modifying the contents of aa.

While in codeblock 3 you are rebinding aaa to another array, and the aaa in function t1 is not a reference to the outside aa anymore. So the outside aa is not being modified.

you can refer to Is JavaScript a pass-by-reference or pass-by-value language? to see the detailed explanation on Javascript's variable passing behavior.

Upvotes: 2

Related Questions