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.
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.
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))
}
<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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With