Why can't we call Date () class methods without a new operator

Suppose I define such a variable

var today = Date(); console.log(today.getMonth()); // Throw Error 

while another class, such as the Error class, calls their methods without a new statement.

 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 a new operator. So, this is the only class that requires a new operator or any technique for creating objects before calling its methods.

Edit: Since Date () is a string type, it should call their methods without creating objects. Because the string type behaves as if they were objects. So why not?

Change 2 . I think this is the only key function that cannot be the same as new Date() like other functions ( Array(), String(), Error() , etc.). Therefore, it is also a hidden function of this language or an ECMAScript error.

+6
source share
3 answers

ECMAScript Language Specification

According to the ECMAScript specification (which Javascript is based on):

When Date is called as a function, not as a constructor, it returns a string representing the current time (UTC).

NOTE. The call to the Date (...) function is not equivalent to the create object of the expression new Date (...) with the same arguments.

Link: http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.2

Calling Constructor vs Calling Function

You need new because you are creating a new Date object. Calling simply Date () means calling a function that returns 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, functions are factory functions that create a new object and return them.

See:

+7
source

It is true that the JavaScript constructor function acts differently when called with or without new . This applies to the Date function, which returns a date as a string when called without new and as a full-fledged object when called with new .

+3
source

The point in using new is to create an instance that inherits the Date prototype.

Which makes it possible for an object to be a receiver of Date functions.

When you use Date() (which, in my opinion, is a useless function), you really get a string equivalent to (new Date()).toString() . Of course, this object only has string functions, not a date.

+1
source

Source: https://habr.com/ru/post/944974/


All Articles