Create a object by onclick JS

Tags: ,



Could someone say is there a method how to create an object by simple click on a button?

function createNewObject() {
// Create here a class
}

// Result should be:
    let car1 = {
      name: "Tesla",
      price: "20$"
    }
<button onclick="createNewObject()"></button>

Answer

You can create a class Car, try this:

class Car {
  constructor(name, price){
    this.name = name,
    this.price = price
  }
}

function createNewObject() {
  let car1 = new Car('Tesla', 20);
  console.log(car1);
}
  
<button onclick="createNewObject()">Generate</button>


Source: stackoverflow