Skip to content
Advertisement

Create a object by onclick JS

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>

Advertisement

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>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement