L
lkrubner
Is it true that Javascript has no clone() method, to pass an object by
copy of value instead of reference?
If I have an object and want to make an array out of all of its
instance variables, I can loop through it and pass its values to a new
array, and the class instances will be passed by copy and not by
reference?
Example 9.3: References Themselves Are Passed by Value
// This is another version of the add_to_totals() function. It doesn't
// work, through, because instead of changing the array itself, it
tries to
// change the reference to the array.
function add_to_totals2(totals, x)
{
newtotals = new Array(3);
newtotals[0] = totals[0] + x;
newtotals[1] = totals[1] + x;
newtotals[2] = totals[2] + x;
totals = newtotals; // this line has no effect outside of the
function.
}
Note that this rule applies not only to pass-by-reference, but also
copy-by-reference. You can modify an object through a copy of a
reference, but changing the copied reference itself does not affect the
object nor the original reference to the object. This is a more
intuitive and less confusing case, so we don't illustrate it with an
example.
copy of value instead of reference?
If I have an object and want to make an array out of all of its
instance variables, I can loop through it and pass its values to a new
array, and the class instances will be passed by copy and not by
reference?
Example 9.3: References Themselves Are Passed by Value
// This is another version of the add_to_totals() function. It doesn't
// work, through, because instead of changing the array itself, it
tries to
// change the reference to the array.
function add_to_totals2(totals, x)
{
newtotals = new Array(3);
newtotals[0] = totals[0] + x;
newtotals[1] = totals[1] + x;
newtotals[2] = totals[2] + x;
totals = newtotals; // this line has no effect outside of the
function.
}
Note that this rule applies not only to pass-by-reference, but also
copy-by-reference. You can modify an object through a copy of a
reference, but changing the copied reference itself does not affect the
object nor the original reference to the object. This is a more
intuitive and less confusing case, so we don't illustrate it with an
example.