Why we can't call methods of Date() class without new operator [duplicate]

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.

Answers:

Answer

ECMAScript Language Specification

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

Calling Constructor vs Calling Function

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:

Answer

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.

Answer

The point in using new is to create an instance inheriting from Date's prototype.

That's what makes possible that the object can be the receiver of Date's functions.

When you use Date() (which is in my opinion a useless function), you're really getting a string which is the equivalent of (new Date()).toString(). Of course this object only has string functions, not the one of Date.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.