What is the difference between `new Object()` and object literal notation?

前端 未结 11 1039
北恋
北恋 2020-11-22 07:41

What is the difference between this constructor-based syntax for creating an object:

person = new Object()

...and this literal syntax:

11条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 08:25

    I have found one difference, for ES6/ES2015. You cannot return an object using the shorthand arrow function syntax, unless you surround the object with new Object().

    > [1, 2, 3].map(v => {n: v});
    [ undefined, undefined, undefined ]
    > [1, 2, 3].map(v => new Object({n: v}));
    [ { n: 1 }, { n: 2 }, { n: 3 } ]
    

    This is because the compiler is confused by the {} brackets and thinks n: i is a label: statement construct; the semicolon is optional so it doesn't complain about it.

    If you add another property to the object it will finally throw an error.

    $ node -e "[1, 2, 3].map(v => {n: v, m: v+1});"
    [1, 2, 3].map(v => {n: v, m: v+1});
                               ^
    
    SyntaxError: Unexpected token :
    

提交回复
热议问题