Why can a constructor be used without `new` keyword in Javascript?
https://softwareengineering.stackexchange.com/questions/285154
-
08-10-2020 - |
Domanda
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?
Soluzione
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.