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

前端 未结 11 775
北恋
北恋 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
      

提交回复
热议问题