Suppose I define a variable like this
var today = Date();
console.log(today.getMonth()); // Throw Error
while other class like Error class call their methods without new operator.
function factorial(x) {
if(x <= 1)
throw Error("x must not be negative");
return x*factorial(x-1);
}
Also wrapper objects (number, boolean, string) can call their methods without new operator. So, Is this the only class which require new operator or any object creation technique before calling their methods.
Edit: As Date() is a string type, so it should be call their methods without creating objects. Because string type behave as if they are objects. So why not?
Edit 2: I think this is the only core function which cannot be same as new Date()
like other functions (Array(), String(), Error()
etc). So, it's also the hidden feature of this language or ECMAScript mistake.
The Date() constructor can create a Date instance or return a string representing the current time.
New keyword in JavaScript is used to create an instance of an object that has a constructor function. On calling the constructor function with 'new' operator, the following actions are taken: A new empty object is created.
The new operator lets developers create an instance of a user-defined object type or of one of the built-in object types that has a constructor function.
The Date object is an inbuilt datatype of JavaScript language. It is used to work with dates and times. The Date object is created by using new keyword, i.e. new Date(). The Date object can be used date and time in terms of millisecond precision within 100 million days before or after 1/1/1970.
According to the ECMAScript specification (on which Javascript is based):
When Date is called as a function rather than as a constructor, it returns a String representing the current time (UTC).
NOTE The function call Date(…) is not equivalent to the object creation expression new Date(…) with the same arguments.
Reference: http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.2
You need the new
because you are creating a new Date
object.
Calling simply Date() , means calling a function that returns the Date() as a string.
See: http://www.javascripture.com/Date
Date() : String
Returns a string representation of the current date and time.
In the case of other types such as Array or Error, the functions are factory functions that create a new object and return them.
See:
http://www.javascripture.com/Array
Error(message : String) : Error Creates a new Error with the specified message that describes the error.
new Error(message : String) : Error Same as Error(message)
It is perfectly valid for a JavaScript constructor function to act differently when called with new
or without. This is the case of the Date
function which returns the date as a string when called without new
and as a full fledged object when called with new
.
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