Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - How can I dynamically create objects during runtime?

I have a constructor:

function car(name, speed, options){
  this.name = name;
  this.speed = speed;
  this.options = options;
}

I can make a new object like so:

var carMustang = new car("Mustang", 250, ["Cruise Control","Air Conditioning", "ABS"]);

If I wanted to have someone click a button, and make new objects dynamically from that button click, how would I go about doing so? I don't want the 'core' object (carMustang) to change, but rather have the option for the user to change the options for their own 'personal' instance of the object. Also, they will need to create multiple instances of the same object, able to change the properties at will- all without affecting the 'core' object defined in code.

like image 851
Kolten Avatar asked Oct 18 '22 08:10

Kolten


1 Answers

Declare a Array to hold all the created cars and make the button on click event call a function that creates a new instance and adds it to the array.

Javascript

var cars = []
function car(name, speed, options){
  this.name = name;
  this.speed = speed;
  this.options = options;
}

function createCar(name, speed, options) {
    cars.push(new car(name, speed, options))
}

HTML

<button onclick="createCar('Mustang', 250, ['Cruise Control','Air Conditioning', 'ABS'])">Create Car</button>

Your variable cars will hold all the created objects and you can retrive them and edit their properties if you want.

like image 50
Danilo Favato Avatar answered Oct 22 '22 06:10

Danilo Favato