joe said:
I need a few clarifications on how Javascript deals with arrays and
Date object.
The same way it deals with all objects.
Lets say daz is a date object. If I do this:
somevar=daz;
then "somevar" with be a pointer to daz,
"somevar" is a *variable*. Variables hold values. In this case the value
it holds is a referencee to a Date object.
"daz" is also a variable. It holds a reference to the same Date object.
The assignment reads the value of the variable "daz" (which is the value
of the variable-expression "daz"), and assigns it to the variable
"somevar".
ie if I change somevar later daz will change also.
That depends on what you mean by "change somevar". If you change the
object referenced by the value in "somevar", e.g., by executing
"somevar.setFullYear(1942)", then that object is changed. Since the
values of "daz" and "somevar" reference the same object, doing
"daz.getFullYear()" will return 1942. The year value sits on the
object, not on the variable.
But If I do this:
somevar=new Date(daz);
somevar will a copy, not a pointer, of daz,
In this case "somevar" will hold a reference to a new Date object.
That Date object was created using the Date constructor with the
object currently referenced by "daz" as parameter.
That constructor is defined to create a new Date object that represents
the same point in time as a parameter Date object.
I.e., "somevar" will hold a reference to a Date object with the same
time as the Date object referenced by "daz". You can call that a "copy"
if you want.
ie if I change somevar later daz will NOT change.
If you change the object referenced by "somevar", then the, different,
object referenced by "daz" will not be changed.
Right? Coming from C/C++ background I tend to think some new memory has been
allocated for "somevar".
That's the error. Objects in Javascript are all heap allocated, as if
created by the C++ "new" operator. I.e., you can think of the
variables as holding a pointer (but it's a pointer that is
automatically dereferenced when you use it, so it's a little more like
a mutable reference variable).
This approach matches the one in Java and C# for "reference-types"
(types where values are represented by a reference, not by their
content).
When will this memory be released?
When the Javascript engine decides that it is no longer needed. The
ECMAScript specification says nothing of memory management. Javascript
engines typically use a garbage collector, but it would be compliant
behavior to never release anything at all, until the program ends.
If you don't crash before that
Can I do it manually somehow if that is the case?
No. You can clear all references to the object, and hope that it
will be garbage collected.
What about arrays? Lets say "bigar" is an array with many items. If I do this
somevar=bigar;
will somevar be a pointer to bigar and not a copy?
Again, you only assign a reference value to "somevar". Both variables
will then refer to the same array.
/L