Kolten
Kolten

Reputation: 3503

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.

Upvotes: 6

Views: 3277

Answers (4)

Danilo Favato
Danilo Favato

Reputation: 283

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.

Upvotes: 3

Carcigenicate
Carcigenicate

Reputation: 45826

Why not just create a "custom constructor" that you call from the click handler?:

function newBaseMustang() {
    var baseMustang = new car("Mustang", 250, ["Cruise Control","Air Conditioning", "ABS"]);

    return baseMustang;
}

Then the caller can make any changes that they want:

var mustang1 = newBaseMustang();
mustang1.speed += 100;

var mustang2 = newBaseMustang();
mustang2.name = "MyMustang";

You could also use a library like Immutable.js to make the "template car" immutable and make modified copies of it.

Upvotes: 0

Eduardo Melo
Eduardo Melo

Reputation: 519

You can clone the object:

var carMustang = new car("Mustang", 250, ["Cruise Control","Air Conditioning", "ABS"]);
var copy = Object.assign({}, carMustang);
console.log(copy);

Upvotes: 0

Lev
Lev

Reputation: 15734

Have users create their own copy of carMustang like this

    click () {
       let userCopy = Object.assign({}, carMustang);
        // then mutate userCopy the way you want 

    }

You might have to clone also objects that are referenced by carMustang

click () {
   let userCopy = Object.assign({}, carMustang, { options: [...carMustang.options]});
}

You can also deepclone carMustang with lodash's clonedeep.

click () {
   let userCopy = _.cloneDeep(carMustang);
}

Upvotes: 0

Related Questions