twesix twesix - 2 months ago 11
Javascript Question

A strange appearance of the arguments in js functioin and object

function modify(t1)
{
t1.t=t1;
}

var t=
{
t:'t'
};

modify(t);

console.log(t);


And the output of the code is : { t: [Circular] }.

I wonder why the operation to the argument changed the value of t out of the function scope.

function another_modify(t1)
{
t1=t1.t;
}

t=
{
t:'t'
};

another_modify(t);

console.log(t);


This time,the output is : { t: 't' }.The t out of the function scope is not changed.

Anyone that gives any tips or help is appreciated.

Answer

I wonder why the operation to the argument changed the value of t out of the function scope.

In the first example, since t is an object and objects are always passed by reference, it is modified in the function.

In your second example, t1=t1.t; assigns a string to the object. I would venture to say that since it is now a string and string variables are passed by value the original object is not changed and retains its object reference to the original.

Comments