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

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

    Everyone here is talking about the similarities of the two. I am gonna point out the differences.

    1. Using new Object() allows you to pass another object. The obvious outcome is that the newly created object will be set to the same reference. Here is a sample code:

      var obj1 = new Object();
      obj1.a = 1;
      var obj2 = new Object(obj1);
      obj2.a // 1
      
    2. The usage is not limited to objects as in OOP objects. Other types could be passed to it too. The function will set the type accordingly. For example if we pass integer 1 to it, an object of type number will be created for us.

      var obj = new Object(1);
      typeof obj // "number"
      
    3. The object created using the above method (new Object(1)) would be converted to object type if a property is added to it.

      var obj = new Object(1);
      typeof obj // "number"
      obj.a = 2;
      typeof obj // "object"
      
    4. If the object is a copy of a child class of object, we could add the property without the type conversion.

      var obj = new Object("foo");
      typeof obj // "object"
      obj === "foo" // true
      obj.a = 1;
      obj === "foo" // true
      obj.a // 1
      var str = "foo";
      str.a = 1;
      str.a // undefined
      
    0 讨论(0)
  • 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/)

    0 讨论(0)
  • 2020-11-22 08:19

    2019 Update

    I ran the same code as @rjloura on my OSX High Sierra 10.13.6 node version 10.13.0 and these are the results

    console.log('Testing Array:');
    console.time('using[]');
    for(var i=0; i<200000000; i++){var arr = []};
    console.timeEnd('using[]');
    
    console.time('using new');
    for(var i=0; i<200000000; i++){var arr = new Array};
    console.timeEnd('using new');
    
    console.log('Testing Object:');
    
    console.time('using{}');
    for(var i=0; i<200000000; i++){var obj = {}};
    console.timeEnd('using{}');
    
    console.time('using new');
    for(var i=0; i<200000000; i++){var obj = new Object};
    console.timeEnd('using new');
    
    
    Testing Array:
    using[]: 117.613ms
    using new: 117.168ms
    Testing Object:
    using{}: 117.205ms
    using new: 118.644ms
    
    0 讨论(0)
  • 2020-11-22 08:24

    Memory usage is different if you create 10 thousand instances. new Object() will only keep only one copy while {} will keep 10 thousand copies.

    0 讨论(0)
  • 2020-11-22 08:25

    Actually, there are several ways to create objects in JavaScript. When you just want to create an object there's no benefit of creating "constructor-based" objects using "new" operator. It's same as creating an object using "object literal" syntax. But "constructor-based" objects created with "new" operator comes to incredible use when you are thinking about "prototypal inheritance". You cannot maintain inheritance chain with objects created with literal syntax. But you can create a constructor function, attach properties and methods to its prototype. Then if you assign this constructor function to any variable using "new" operator, it will return an object which will have access to all of the methods and properties attached with the prototype of that constructor function.

    Here is an example of creating an object using constructor function (see code explanation at the bottom):

    function Person(firstname, lastname) {
        this.firstname = firstname;
        this.lastname = lastname;
    }
    
    Person.prototype.fullname = function() {
        console.log(this.firstname + ' ' + this.lastname);
    }
    
    var zubaer = new Person('Zubaer', 'Ahammed');
    var john = new Person('John', 'Doe');
    
    zubaer.fullname();
    john.fullname();
    

    Now, you can create as many objects as you want by instantiating Person construction function and all of them will inherit fullname() from it.

    Note: "this" keyword will refer to an empty object within a constructor function and whenever you create a new object from Person using "new" operator it will automatically return an object containing all of the properties and methods attached with the "this" keyword. And these object will for sure inherit the methods and properties attached with the prototype of the Person constructor function (which is the main advantage of this approach).

    By the way, if you wanted to obtain the same functionality with "object literal" syntax, you would have to create fullname() on all of the objects like below:

    var zubaer = {
        firstname: 'Zubaer',
        lastname: 'Ahammed',
        fullname: function() {
            console.log(this.firstname + ' ' + this.lastname);
        }
    };
    
    var john= {
        firstname: 'John',
        lastname: 'Doe',
        fullname: function() {
            console.log(this.firstname + ' ' + this.lastname);
        }
    };
    
    zubaer.fullname();
    john.fullname();
    

    At last, if you now ask why should I use constructor function approach instead of object literal approach:

    *** Prototypal inheritance allows a simple chain of inheritance which can be immensely useful and powerful.

    *** It saves memory by inheriting common methods and properties defined in constructor functions prototype. Otherwise, you would have to copy them over and over again in all of the objects.

    I hope this makes sense.

    0 讨论(0)
  • 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 :
    
    0 讨论(0)
提交回复
热议问题