JS: Date()
In JS, objects are normally constructed using the new
operator:
new Blob()
// Blob { ... }
new Number(7)
// Number { 7 }
This is useful for constructing lots of things: Blob
, MutationObserver
, Date
, and much more.
Different built-in types will do different things if their constructors are invoked without new
:
// Most new types will return an error
Blob()
// Error: Failed to construct 'Blob': Please use the 'new' operator,
// this DOM object constructor cannot be called as a function.
// Some other types roll with the punches
Array()
// []
// JavaScript's boxed primitive types return the underlying primitive instead
Number(7)
// 7
Date is not one of these types.
new Date()
// Tue Dec 22 2020 01:01:16 GMT-0800 (Pacific Standard Time)
typeof new Date()
// object
Date()
// "Tue Dec 22 2020 01:01:26 GMT-0800 (Pacific Standard Time)"
typeof Date()
// string