Skip to content Skip to sidebar Skip to footer

Why We Can't Call Methods Of Date() Class Without New Operator

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.

Solution 1:

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 currentdateand 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:

Solution 2:

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.

Solution 3:

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.

Post a Comment for "Why We Can't Call Methods Of Date() Class Without New Operator"