Can we omit parentheses when creating an object using the “new” operator?

前端 未结 6 2158
清酒与你
清酒与你 2020-11-22 00:41

I have seen objects being created this way:

const obj = new Foo;

But I thought that the parentheses are not optional when creating an objec

6条回答
  •  孤城傲影
    2020-11-22 00:51

    https://people.mozilla.org/~jorendorff/es6-draft.html#sec-new-operator-runtime-semantics-evaluation

    Here's the part of the ES6 spec that defines how the two variants operate. The no-parentheses variant passes an empty argument list.

    Interestingly, the two forms have different grammatical meanings. This comes up when you try to access a member of the result.

    new Array.length // fails because Array.length is the number 1, not a constructor
    new Array().length // 0
    

提交回复
热议问题