Reputation: 5301
I played with javascript and this is it :
> var obj = new Object();
> obj
{}
> obj.x = 0;
0
> function change_x(o) { o.x = o.x + 1; }
> change_x(obj);
> obj
{ x: 1 }
> function change_obj(o) { o = null; }
> change_obj(obj);
> obj
{ x: 1 }
function change_obj_x(o) { console.log(o); o.x = o.x + 1; o = null; console.log(o); }
> change_x(obj)
> change_obj_x(obj);
{ x: 2 }
null
> obj
{ x: 3 }
When i passed obj
to change_x
, it made changes into the obj itself, but when i tried to make obj null
by passing it to change_obj
, it did not changed the obj. Nor change_obj_x
did what i expected.
Please explain this and give me some links to know everything about functions.
Upvotes: 1
Views: 120
Reputation: 3968
See Functions
If you pass an object (i.e. a non-primitive value, such as Array or a user-defined object) as a parameter, and the function changes the object's properties, that change is visible outside the function
Note that assigning a new object to the parameter will not have any effect outside the function, because this is changing the value of the parameter rather than the value of one of the object's properties
There is a great explanation:
Imagine your house is white and you give someone a copy of your address and say, "paint the house at this address pink." You will come home to a pink house.
That's what you did in
> function change_x(o) { o.x = o.x + 1; }
> change_x(obj);
And
Imagine you give someone a copy of your address and you tell them, "Change this to 1400 Pennsylvania Ave, Washington, DC." Will you now reside in the White House? No. Changing a copy of your address in no way changes your residence.
That's what
> function change_obj(o) { o = null; }
> change_obj(obj);
do.
Upvotes: 0
Reputation: 7320
When you assign something to o
in a function like in
function change_obj(o) { o = null; }
you don't change the parameter but just assign null
to the variable. As the o
variable doesn't exists outside the function, nothing happens.
In contrast,
function change_x(o) { o.x = o.x + 1; }
changes the parameter itself. As the parameter is passed by reference, the value of the x
property is also changed outside the function.
In your function function change_obj_x(o)
, you combine these two effects. At first, you change the x
property of o
(which references to your obj
), and then you assign null
to o
. The latter doesn't influence obj
.
Upvotes: 3