koljanep Posted October 17, 2011 Share Posted October 17, 2011 Hi, I am just doing the "Date()" Object Tutorial on the w3schools site. In literally all the examples instead of "Date();" it says "new Date();" I tried to figure out why but there is no explanation whatsoever what this new has to do with the Date object. I tried to delete the new from the examples. Some stop working, some still work without new in them. Can someone explain what this is all about? Here some example code: <html><body> <script type="text/javascript"> var d = new Date();d.setFullYear(1992,10,3);document.write(d); </script> </body></html> Link to comment Share on other sites More sharing options...
thescientist Posted October 17, 2011 Share Posted October 17, 2011 it's to create a new and unique instance of the date object. It helps to familiarize one's self with the meaning of the new keyword though.http://stackoverflow.com/questions/383402/is-javascript-s-new-keyword-considered-harmful Link to comment Share on other sites More sharing options...
Ingolme Posted October 17, 2011 Share Posted October 17, 2011 It creates an instance of the date object. You could have two different dates.For example: var a = new Date();a.setFullYear(2009);var b = new Date();b.setFullYear(2011)alert(a.getFullYear());alert(b.getFullYear()); Link to comment Share on other sites More sharing options...
justsomeguy Posted October 17, 2011 Share Posted October 17, 2011 The Date object itself is a single object instance. Like you found out, some code works if you're just using the global Date object. If you want to work with individual dates you need to create new objects, which is where you use the new keyword. It will sort of create a copy of the global object but it won't have any changes you made to the global one, it starts new. By default it's set to the current date and time. Link to comment Share on other sites More sharing options...
koljanep Posted October 17, 2011 Author Share Posted October 17, 2011 All right, thanks! I understood now what it does! Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.