Differences between object literals and new keyword instantiation objects

var t1 = [];
var t2 = [];
var arr = [
  {
    id: 1,
    name: "a1"
  },
  {
    id: 2,
    name: "a2"
  },
  {
    id: 3,
    name: "a3"
  }
]

function test(id, name) {
  this.id = id
  this.name = name
  this.idAndName = id + name
}

arr.forEach((item, index) => {
  // 1
  t1.push({
    id: item.id,
    name: item.name,
    idAndName: item.id + item.name
  })

  // 2new
  t2.push(new test(item.id, item.name));
})
console.log(t1, t2);
Which of the above two ways of writing is better? What"s the difference

Apr.01,2021

is of course literal, concise, fast, and the key is that you can type a lot of code less


the answer is not necessarily.
depends on whether your data deconstruction will be massively reused.
assume that the structure is like this
We temporarily call it obj

{
    a:[
        {a1:"foo",a2:"bar"},
        {a1:"baz",a2:"bar"},
    ],
    b:"hello",
    c:"world",
    //...
    z:"too much",
}

if you need to write this in many places
, it's painful every time you write it, or even paste it.

or
you have a method that requires that the parameters passed in must be of a structure like obj.
if you create an instance with the new keyword, you can quickly use instanceof to determine
. On the contrary, you have to check each attribute

.
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3a70d-41255.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3a70d-41255.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?