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

前端 未结 11 1060
北恋
北恋 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:27

    They both do the same thing (unless someone's done something unusual), other than that your second one creates an object and adds a property to it. But literal notation takes less space in the source code. It's clearly recognizable as to what is happening, so using new Object(), you are really just typing more and (in theory, if not optimized out by the JavaScript engine) doing an unnecessary function call.

    These

    person = new Object() /*You should put a semicolon here too.  
    It's not required, but it is good practice.*/ 
    -or-
    
    person = {
        property1 : "Hello"
    };
    

    technically do not do the same thing. The first just creates an object. The second creates one and assigns a property. For the first one to be the same you then need a second step to create and assign the property.

    The "something unusual" that someone could do would be to shadow or assign to the default Object global:

    // Don't do this
    Object = 23;
    

    In that highly-unusual case, new Object will fail but {} will work.

    In practice, there's never a reason to use new Object rather than {} (unless you've done that very unusual thing).

提交回复
热议问题