3

I found Date can be used without the new keyword.

Date(1)
> "Thu May 28 2015 15:54:20 GMT+0800 (CST)"
new Date(1)
> Thu Jan 01 1970 08:00:00 GMT+0800 (CST)

I was wondering whether there is any side-effect of using it without new.. Why would it be designed like this?

4

In JavaScript a constructor is just an ordinary function. Any function which can be called as a constructor with 'new' can be called as an ordinary function. But functions will almost always be written as either a constructor or non-constructor function, and using it the other way is an error.

The built-in objects however are specifically designed so that you can use them both ways (as constructor and as ordinary functions) with two different results. For example new Date(1) creates a new Date object (as you would expect for a constructor) while Date(1) returns a string representation of the corresponding date, which is perhaps more surprising.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.