7

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?

Aurelio De Rosa
  • 21,856
  • 8
  • 48
  • 71
Andrew Young
  • 1,779
  • 1
  • 13
  • 27

2 Answers2

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.

Community
  • 1
  • 1
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 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
  • I have no idea why they wrote that. – SLaks Nov 23 '11 at 01:18
  • 1
    it 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 " (where is "()"). – Dmitry B. Nov 23 '11 at 01:46
  • @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