Parenthesis-Free Object Creation with the "new" Operator
The creation of objects with the "new" operator using the former way:
const obj = new Foo;
is valid and defined in the ECMAScript standard. The omission of parentheses is allowed only for the "new" operator when there are no arguments in the function call.
Both methods of object creation achieve the same result, but there are subtle differences. When using the parenthesis-free syntax, the engine implicitly supplies the parentheses, which can lead to unexpected behavior if the code is modified later. For example, if you accidentally insert an argument after adding parentheses:
const obj = new Foo(argument);
the code will break because the "new" operator cannot be invoked with arguments when created without parentheses.
On the other hand, using the parentheses with an empty argument list explicitly declares the absence of arguments, preventing such errors. Additionally, JSLint recommends using parentheses, as it detects missing parentheses when invoking constructors.
While both forms are valid, using parentheses is preferred for consistency, clarity, and to avoid potential pitfalls.
The above is the detailed content of Should You Use Parentheses with the `new` Operator in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!