I'm studying objects in JavaScript and confused when the new keyword and () are required when using a object creation expression.
var a = new Date(); // current date and time
var b = Date(); // current date and time
var c = new Date; // current date and time
var d = Date; // => function Date() { [native code] }
Is there any difference in the first three methods? Why doesn't d do as expected?
Given: new Date()
This is the "standard" way to create a new object from a constructor-function1; it returns a new Date object representing the current time.
Given: Date()
JavaScript defines the Date function to operate like this when not called as a constructor (ie. with new). It returns a different value - a string and not a Date object - than new Date(). See Why we can't call methods of Date() class without new operator.
User-code can also check the value of this inside a constructor-function to determine if new was used, although this is only done relatively infrequently. See How to detect if a function is called as constructor?
Given: new Date
When using new the parenthesis are optional if there are no arguments. This is just an additional syntax form that most people don't use - it is equivalent to new Date() if the expression is terminated. See Can we omit parentheses when creating an object using the "new" operator?
Given: Date
This evaluates the expression to the constructor-function (which is just a function-object!2) without invoking it or creating a new instance. This is why the result shows a "function" - it is the constructor-function.
1 I use the term constructor-function to emphasis the point that a constructor is only a function that [also] supports new; it is technically sufficient to call it a constructor.
2 Likewise, it is important to understand that function[-objects]s in JavaScript are first-class citizens and thus just values themselves; like any object. In the last example the assignment of the object/value occurred without performing any action (ie. function invocation) upon the object itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With