要在javascript中创建一个新的空对象,我们可以用2种方式编写。 1.使用对象文字语法:
const obj = {}
2.或使用构造函数的语法:
const obj = new Object()
Today I accidentally typed out const obj = new Object
saw it also worked, where it should've thrown
an error because I'd not invoked the constructor function which is done by a set of parenthesis.
I know that the new
operator with a constructor function does 3 things.
1. creates a new empty object.
2. sets the value of this
to the new object.
3. return the newly created object from the constructor function.
构造函数调用是可选的吗? 那我想念什么呢?
作为一种特殊情况,仅对于new运算符,JavaScript通过在函数调用中没有参数的情况下省略括号来简化语法。以下是使用new运算符的一些示例:
Originally answered here.