473,769 Members | 2,359 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

javascript and pointers

joe
I need a few clarifications on how Javascript deals with arrays and Date object.

Lets say daz is a date object. If I do this:

somevar=daz;

then "somevar" with be a pointer to daz, ie if I change somevar later daz will
change also. But If I do this:

somevar=new Date(daz);

somevar will a copy, not a pointer, of daz, ie if I change somevar later daz will
NOT change.

Right? Coming from C/C++ background I tend to think some new memory has been
allocated for "somevar". When will this memory be released? Can I do it manually
somehow if that is the case?
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?
Jun 27 '08 #1
6 1833
VK
On Apr 13, 2:29 pm, joe <m...@invalid.c omwrote:
I need a few clarifications on how Javascript deals with arrays and Date object.

Lets say daz is a date object. If I do this:

somevar=daz;

then "somevar" with be a pointer to daz, ie if I change somevar later daz will
change also. But If I do this:

somevar=new Date(daz);

somevar will a copy, not a pointer, of daz, ie if I change somevar later daz will
NOT change.
Your sample doesn't have sense in the context of your question. Date
constructor expects primitives, so providing daz being type of object
just leads to invalid date result. What you meant I guess is something
like somevar=new Object(daz); or similar

Any way, Javascript implements automated garbage collection similar to
Java, so with a proper programming you don't care of destructors -
this phenomenon as such is totally alien to Javascript.

If you are curious of the background mechanics of the process then I
once wrote about it here:
http://groups.google.com/group/comp....ed90f1c1b4ccef

Do not hesitate to ask if more questions remain.
Jun 27 '08 #2
joe <mt@invalid.com writes:
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.setFul lYear(1942)", then that object is changed. Since the
values of "daz" and "somevar" reference the same object, doing
"daz.getFullYea r()" 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
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Jun 27 '08 #3
VK <sc**********@y ahoo.comwrites:
Your sample doesn't have sense in the context of your question. Date
constructor expects primitives, so providing daz being type of object
just leads to invalid date result.
Actually, if d is a Date objet, then
new Date(d)
is equvialent to
new Date(d.valueOf( ))
which is again equivalent to
new Date(d.getTime( ))
which indeed creates a Date object with the same time value as the
original.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Jun 27 '08 #4
VK
Your sample doesn't have sense in the context of your question. Date
constructor expects primitives, so providing daz being type of object
just leads to invalid date result.

Actually, if d is a Date objet, then
new Date(d)
is equvialent to
new Date(d.valueOf( ))
which is again equivalent to
new Date(d.getTime( ))
which indeed creates a Date object with the same time value as the
original.
Indeed. I am not an engine torturer by my nature :-), so never
explored this variant. Still I guess OP question is about generic
language features and not about particular AID (Anti-Idiot Defence)
mechanics build into language. :-)
Jun 27 '08 #5
In comp.lang.javas cript message <r6**********@h otpop.com>, Sun, 13 Apr
2008 14:10:03, Lasse Reichstein Nielsen <lr*@hotpop.com posted:
>VK <sc**********@y ahoo.comwrites:
>Your sample doesn't have sense in the context of your question. Date
constructor expects primitives, so providing daz being type of object
just leads to invalid date result.

Actually, if d is a Date objet, then
new Date(d)
is equvialent to
new Date(d.valueOf( ))
which is again equivalent to
new Date(d.getTime( ))
which indeed creates a Date object with the same time value as the
original.
JavaScript new Date() likes to receive a string argument, and a Date
Object likes to provide a String. The equivalence is thus to
new Date(d.toString ()). Or so I thought from using IE4 IE6 IE7.

Using d.toString() provides a correct representation of the value of the
Date Object, but truncated to the Second.

Therefore, such a copy will be unfaithful to a degree which is often
unimportant. Proof : execute (I used js-quick.htm)
d1 = new Date()
d2 = new Date(d1)
x = [d1%1000, d2%1000]
I get in IE7 [Random(1000),0]; in FF2, Op9, Sf3 [Random(1000),sa me]; I
had expected that all would follow IE.

That, naturally, leads those who only test in a reputable browser to
write code which may err in a common one.

Moreover, although d.toString() only makes a small error, new Date(d)
can make a rather large one if presented with dates in some or all years
in 99BC to 99AD inclusive; it adds, or at least can add, 1900 years.
Trying :
d1 = new Date(100,0,0) // Year 99, Dec 31
d2 = new Date(d1)
x = [d1, d2]
I get d2 in 1899 in IE but d2 in 0099 in the other three.

For both tests, new Date(+d1) always gives an accurate copy.

Consider now timing :
K_ = ???
D0_ = new Date()
Q_ = K_ ; while (Q_--) { }
D1_ = new Date()
Q_ = K_ ; while (Q_--) { new Date(D0_) }
D2_ = new Date()
Q_ = K_ ; while (Q_--) { new Date(+D0_) }
D3_ = new Date()
Q_ = [D1_-D0_, D2_-D1_, D3_-D2_] // Demo 6
->
IE7 K=5e4 Result 16,953,297
FF2 K=5e4 Result 94,500,515
Op9 K=5e4 Result 31,141,125
Sf3 K=5e5 Result 157,406,562 // Note bigger K

Therefore, one should use the + if the code might be executed mainly in
IE, and should omit it if the code might be executed mainly in Safari;
but one must use the + for full range work where IE is possible.
The benefits of that + were discussed here a while ago; perhaps in the
regrettable period where we were not honoured by LRN's presence. I then
had only IE4; and there were no reports of differences with other
browsers.

--
(c) John Stockton, nr London, UK. ?@merlyn.demon. co.uk Turnpike v6.05.
Web <URL:http://www.merlyn.demo n.co.uk/- w. FAQish topics, links, acronyms
PAS EXE etc : <URL:http://www.merlyn.demo n.co.uk/programs/- see 00index.htm
Dates - miscdate.htm moredate.htm js-dates.htm pas-time.htm critdate.htm etc.
Jun 27 '08 #6
Dr J R Stockton <jr*@merlyn.dem on.co.ukwrites:
In comp.lang.javas cript message <r6**********@h otpop.com>, Sun, 13 Apr
2008 14:10:03, Lasse Reichstein Nielsen <lr*@hotpop.com posted:
>>Actually, if d is a Date objet, then
new Date(d)
is equvialent to
new Date(d.valueOf( ))
....
JavaScript new Date() likes to receive a string argument, and a Date
Object likes to provide a String. The equivalence is thus to
new Date(d.toString ()). Or so I thought from using IE4 IE6 IE7.
I don't know about IE, but according to the ECMAScript specification,
the conversion happens as:

Call to the Date constructor with a single argument (15.9.3.2) constructs
a new Date object with a [[Value]] computed by calling ToPrimitive
on the argument (with no hint).
According to 9.1, this calls [[DefaultValue]] on the object.
According to 8.6.2.6, this is interpreted as having the hint/preferred
type "number", which then calls the "valueOf" method on the object.
According to 15.9.5.8 this returns the time value of a Date object.

I.e., no strings.

A specification doesn't guarantee that browsers are compliant, ofcourse :)
Using d.toString() provides a correct representation of the value of the
Date Object, but truncated to the Second.
To check whether there is rounding to the second, as string conversion would
cause, the following code can be used:
var d = new Date(1972,02,28 ,23,50,12,987);
var dd = new Date(d);
var dn = new Date(Number(d)) ;
var ds = new Date(String(d)) ;
alert([dd.getMilliseco nds(),
dn.getMilliseco nds(),
ds.getMilliseco nds()].join("\n"));

In Opera, both dd and dn preserves milliseconds, and ds doesn't.
Ditto in Firefox.
However, in IE7, dd loses milliseconds too, so it appears that
IE is not spec-compliant at that point.
Therefore, one should use the + if the code might be executed mainly in
IE, and should omit it if the code might be executed mainly in Safari;
but one must use the + for full range work where IE is possible.
Indeed, to copy a date, one should do one of these, equivalent, calls:
new Date(+d)
new Date(Number(d))
new Date(d.valueOf( ))
new Date(d.getTime( ))

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Jun 27 '08 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1782
by: ArShAm | last post by:
Hi there Where can I download a complete javascript function list? Thanks ArShAm
6
2314
by: Nou Dadoun | last post by:
I'm currently developing an application in C++/MFC (Visual Studio 6, if that makes a difference) and I'd like to avoid the Windows style UI widgets and dialogs if at all possible. In fact, what I'd really like to do is use HTML/web pages as the user interface and invoke my application in the background to do the heavy lifting. I'm fairly well experienced with web pages and I've written a fair amount of JavaScript at one time or another...
9
2896
by: Robby Bankston | last post by:
I'm working on some code and am running into brick walls. I'm trying to write out Javascript with Javascript and I've read the clj Meta FAQ and didn't see the answer, read many similar posts (with no luck though), and searched through the IRT.ORG Faqs (www.irt.org/script/script.htm). The Javascript is designed to open an popup window and then inside that window call another script which will resize that window. There may be another...
6
5581
by: ged | last post by:
Hi, i am a oo (c#) programmer, and have not used javascript for a while and i cant work out how javascript manages its references. Object References work for simple stuff, but once i have an object collection and stanrd using it it starts to fall apart. Clearly there is something about javascript's usage of passing "By ref" that i am not getting. i have had a look on the web and found some examples, but i cant see why my code does not...
7
19257
by: James Johnson | last post by:
Are there structs in JavaScript? If not, what's the closest thing, or do I just use parallel arrays? I'm populating a JavaScript array from ColdFusion query, but I don't think I can do this: var location = new Array() <cfloop query="loc"> location.name = '#loc.name#' location.address1 = '#loc.address1#'
1
1785
by: ArcInversion | last post by:
Hi, I've been using a javascript script to create a dragon that flies across the page. Anyways, I'd like to make it so when you click the dragon it takes you to a new page. Was wondering if anyone could help me out here. Below is the complete script. <SCRIPT language="JavaScript1.2"> var cursorpath="http://i68.photobucket.com/albums/i9/worklog_halcyon/Misc/pet1_lohi_dog.png" if (document.layers)
1
2431
by: Harry Haller | last post by:
What is the fastest way to search a client-side database? I have about 60-65 kb of data downloaded to the client which is present in 3 dynamically created list boxes. The boxes are filled from 3 string arrays, which are just lists of people or companies in alphabetic order. These names may have accented and umlauted characters (which are present as the plain ASCII - not as the entity &# character). The page is UTF-8 encoded. e.g. ...
18
1931
by: Tom Cole | last post by:
I'm working on a small Ajax request library to simplify some tasks that I will be taking on shortly. For the most part everything works fine, however I seem to have some issues when running two requests at the same time. The first one stops execution as the second continues. If I place either an alert between the two requests or run the second through a setTimeout of only 1 millisecond, they both work. You can see a working example here:...
20
2301
by: shapper | last post by:
Hello, How to create a namespace in Javascript containing two methods? And how to access those methods? Thanks, Miguel
4
3122
by: Joe Hrbek | last post by:
Could someone help me translate to something that would close to it in python? The anonymous functions are giving me problems. var dataListener = { data : "", onStartRequest: function(request, context){}, onStopRequest: function(request, context, status){ instream.close(); outstream.close(); listener.finished(this.data);
0
9423
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10043
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9990
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9861
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7406
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5446
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3956
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3561
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2814
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.