In javascript, the typical way to new up an object is by doing it like this: new Date()
. But you can also do this: new (Date)
. What is the difference and advantages of doing it the latter way?
Asked
Active
Viewed 209 times
7

Aurelio De Rosa
- 21,856
- 8
- 48
- 71

Andrew Young
- 1,779
- 1
- 13
- 27
-
9`new (Date)` is annoying as I have to go "Wait, what?" and read it again – Raynos Nov 23 '11 at 01:01
-
Where did you see that crazy mark-up? – epascarello Nov 23 '11 at 01:05
-
You can write new Date; as well. But there is no difference like SLaks described below. – Wojciech Bednarski Nov 23 '11 at 01:11
-
@epascarello see comment for SLaks below for where I saw an example of this. – Andrew Young Nov 23 '11 at 01:15
2 Answers
11
There is no difference.
The new
operator takes a function reference.
Like any other operator, the operand can have parentheses.
The ()
after a new
expression with no arguments are optional.
However, if you have more a complicated expression inside the parentheses, they can change precedence ordering, such as in this answer.
-
so you're saying that the guys that wrote the [usage guide](http://lesscss.org/#-client-side-usage) on lesscss.org really had no reason to write it like this? `var parser = new(less.Parser);` other than to create confusion? They could have written it like `new less.Parser()`? – Andrew Young Nov 23 '11 at 01:12
-
-
1it seems like there is a difference (at least I'm seeing one in Chrome). Try: new Date().toString() vs new(Date).toString() – Dmitry B. Nov 23 '11 at 01:37
-
1@DmitryBeransky Yes, and it makes sense, at least after working out why :-) The grammar accepted is `new ctorExpr` or `new ctorExpr(...)` in the latter case the `ctorExpr` is taken as `(Date).toString`, which is not a valid constructor and thus it vomits. That is, the latter is parsed as `new ((Date).toString) ()` whereas the former is `(new (Date)()).toString()`. This doesn't change `(...)` being optional or required, although it does change how it's parsed. – Nov 23 '11 at 01:41
-
yes, makes sense. But this means that what SLaks said about the parentheses is not exactly right (well, slightly confusing). The parentheses are not part of "new," they are part of the expression. In other words it's not "new(
)", but rather "new – Dmitry B. Nov 23 '11 at 01:46" (where is "( )"). -
@DmitryBeransky: That's what I meant by saying that the _operand_ can have parentheses. Your other examples are what I allude to in the last paragraph. – SLaks Nov 23 '11 at 03:27
0
I believe the latter way is identical to the first way. I think it will be interpreted as new Date
since there is nothing to evaluate in the parentheses. Note that new Date
is equivalent to new Date()
.

Ben
- 10,056
- 5
- 41
- 42