Why do I need the `new` keyword for an instance of `Date` in JavaScript?

Viewed 2300

I understand the difference in behavior. Date() returns a String representing the current date, and new Date() returns an instance of the Date object whose methods I can call.

But I don't know why. JavaScript is prototyped, so Date is a function and an object which has member functions (methods) which are also objects. But I haven't written or read any JavaScript that behaves this way, and I'd like to understand the difference.

Can somebody show me some sample code of a function that has a method, returns an instance with the new operator, and outputs a String when called directly? i.e. how does something like this happen?

Date();                   // returns "Fri Aug 27 2010 12:45:39 GMT-0700 (PDT)"
new Date();               // returns Object
new Date().getFullYear(); // returns 2010
Date().getFullYear();     // throws exception!

Very specific request, I know. I hope that's a good thing. :)

2 Answers
Related