When is * not * new work on built-in modules used?

When playing with built-in objects and JavaScript constructors, I noticed something a bit strange.

Sometimes you can get new objects by calling the constructor without new . For instance:

 > new Array(1,2,3,4) [1, 2, 3, 4] > Array(1,2,3,4) [1, 2, 3, 4] 

But sometimes this does not work:

 > Date() "Thu Jun 05 2014 00:28:10 GMT-0600 (CST)" > new Date() Date 2014-06-05T06:28:10.876Z 

Is the behavior of inline functions of a non-new constructor defined in the ECMAScript specification? Please note that this behavior is really useful; I can make an unsharp copy of the array by calling Array.apply(arr) , but I would feel comfortable if it were cross-platform.

+6
source share
2 answers

The behavior of the native method depends on the EcmaScript specification.

For Date specification says:

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 creation expression of a new Date (...) object with the same arguments.

and for Array spec says

When Array is called as a function, not as a constructor, it creates and initializes a new Array object.

Thus, the call to the Array (...) function is equivalent to the creation expression of the new Array (...) object with the same arguments.

So, how it works with or without the new keyword depends entirely on which method you use and what the spec says when it is called without a new keyword.

For example, the Math object is again different.

The Math object does not have an internal [[Construct]] property; It is impossible to use the Math object as a constructor with the new Operator.

+1
source

Yes, ECMA-262 (I use the 5.1 edition for reference) defines how object constructors should work when called with or without new .

For Array :

15.4.1 Array constructor called as a function :

When Array is called as a function, not as a constructor, it creates and initializes a new Array object. Thus, the call to the Array(…) function is equivalent to the creation expression of the new Array(…) object with the same arguments.

15.4.2 Array constructor :

When Array is called as part of the new expression, it is a constructor: it initializes the newly created object.

For Date :

15.9.2 Date constructor called as a function :

When Date is called as a function, not as a constructor, it returns a string representing the current time (UTC).
Calling the Date(…) function is not equivalent to creating a new Date(…) object with the same arguments.

15.9.3 Date constructor :

When Date is called as part of a new expression, it is a constructor: it initializes a newly created object.

+1
source

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


All Articles