Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a new object on click

Good Day, My question might be a bit 'newbie' but I am! I have an object like this:

var person = {
   firstName: null, 
   lastName: null, 
   age: null, 
   eyeColor: null
};

So when I click a button to 'add' a new person (a new object), I would like to have something like this...

$("p").click(function(){
    var newPerson = new Person("John", "Doe", "50", "blue");
    console.log("A new person has been created!");
});

But this scenario is good for one object... How can I create 'many' new persons with different parameters, and especially different object names (var newPerson) ? I know I can have a function with parameters, but the names of the objects remain the same, so the object is replaced by the new one... I hope I'm clear... Or at least somebody will understand me! Thank You! :)

like image 681
EricF Avatar asked Feb 19 '26 01:02

EricF


1 Answers

When you use the var keyword with the same label, it switches the object to which you're referring, so really the problem is finding a place to store your instances of the People class rather than creating different variable names. Something like this could work:

var people = [];

$("p").click(function(){
    var newPerson = new Person("John", "Doe", "50", "blue");
    people.push(newPerson);
    console.log("A new person has been created!");
});

This way, you can just refer to different people with the index at which they are stored in your people array.

console.log(people[0]) //-> {firstName: "John", lastName: "Doe", age: 50, eyeColor: "blue"}

Hope this helps!

like image 199
kqcef Avatar answered Feb 21 '26 14:02

kqcef



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!