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

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

    In JavaScript, we can declare a new empty object in two ways:

    var obj1 = new Object();  
    var obj2 = {};  
    

    I have found nothing to suggest that there is any significant difference these two with regard to how they operate behind the scenes (please correct me if i am wrong – I would love to know). However, the second method (using the object literal notation) offers a few advantages.

    1. It is shorter (10 characters to be precise)
    2. It is easier, and more structured to create objects on the fly
    3. It doesn’t matter if some buffoon has inadvertently overridden Object

    Consider a new object that contains the members Name and TelNo. Using the new Object() convention, we can create it like this:

    var obj1 = new Object();  
    obj1.Name = "A Person";  
    obj1.TelNo = "12345"; 
    

    The Expando Properties feature of JavaScript allows us to create new members this way on the fly, and we achieve what were intending. However, this way isn’t very structured or encapsulated. What if we wanted to specify the members upon creation, without having to rely on expando properties and assignment post-creation?

    This is where the object literal notation can help:

    var obj1 = {Name:"A Person",TelNo="12345"};  
    

    Here we have achieved the same effect in one line of code and significantly fewer characters.

    A further discussion the object construction methods above can be found at: JavaScript and Object Oriented Programming (OOP).

    And finally, what of the idiot who overrode Object? Did you think it wasn’t possible? Well, this JSFiddle proves otherwise. Using the object literal notation prevents us from falling foul of this buffoonery.

    (From http://www.jameswiseman.com/blog/2011/01/19/jslint-messages-use-the-object-literal-notation/)

提交回复
热议问题