Jump to content

"new" Date();?


koljanep
 Share

Recommended Posts

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> 

  • Like 1
Link to comment
Share on other sites

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

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

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...