10.5 Passing Function Arguments by Reference
Professor: We now take a little closer look at what happens when a n argument is
passed to a function by reference. Consider the following example:
var x = [3, 2, 5];
var myFunc = function(y) {
y[0] = 10;
};
myFunc(x);
console.log(x); //Writes [10, 2, 5]
Because x is an object, a ref erence to the objec t is copied to the function parameter
y when we call the myFunc() fu nction. Inside the fun ction, we assign the value 10
to the first element of an array. Since y refers to the same global array as x does, the
global array is cha nged and the last line of the code prints the changed array to the
JavaScript Console.
Let me give you a slightly m odified example:
var x = [3, 2, 5];
var myFunc = function(y) {
y = 10;
};
myFunc(x);
console.log(x);
What do you think happ ens n ow?
Mike: I guess that th e array is now overridden by the value 10, so the program writes
out 10.
Professor: Does it really? The statement y = 10 ; indeed overrides the array. How-
ever, it does not override the array proper, it only changes one of the two references
to the arr ay. The result is that y simply does not refer to the array object any more.
By changing the value of y we the refore do not change either x or the array object it
refers to, and the program writes out the unchanged array [3, 2, 5].
Maria: That is a little confusing. How can I tell the dierence?
Professor: Let’s use our analogy of boxes once more. The variable x is a bo x holding
a piece of paper, on which the location of the array [3 , 2, 5] is written. When we
call the myFunc() function, we eectively copy that piece of pape r and put it into
another box named y. Now, in our second example, we simply replace that copy with
the value 10, which obviously cannot c hange the original object. In the first example,
however, we do not replace th e contents of the box w ith another value. In the first
example, the program is ordered to do something with the object to which the pa per in
the box refers. The situation is the same every time wh en you use an access operator
on an object. In the following program, for example, the original array is truncated
and then sorted:
200 Meeting 10. Understa nding Functions
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.95.150