If I write a function that creates a new person and attach it to an onClick event on a button, how can I access the data that was entered without a variable name?
When a user presses the button, the user can enter values when prompts come up, but nothing prints to the console upon completion?
I tried the followng code:
<button type="submit" onClick="addNewPerson()">Add New Person</button>
class Person {
constructor(fname, lname, birthDate) {
this.firstName = fname;
this.lastName = lname;
this.dov = birthDate;
}
}
let person1 = new Person("Mark", "Johnson", "12-07-1972");
let person2 = new Person("John", "Miller", "08-017-1923");
function addNewPerson() {
let ffname = prompt("enter your firstname", "Roger");
let llname = prompt("enter your lastname", "Doger");
let ddov = prompt("enter your date of birth", "July 6 2024");
return new Person(ffname, llname, ddov);
}
console.log(addNewPerson())
console.log(person1);
console.log(person2);
console.log(new Person(this.fname, this.lname, this.birthDate));
What I was expecting - When the button is clicked, the values entered into the prompts would be displayed in the console. It does not. This code only prints the following to the console:
Object { firstName: "Roger", lastName: "Doger", dov: "July 6 2024" }
Object { firstName: "Mark", lastName: "Johnson", dov: "12-07-1972" }
Object { firstName: "John", lastName: "Miller", dov: "08-017-1923" }
Object { firstName: undefined, lastName: undefined, dov: undefined }
The dynamically created person objects are not being stored or referenced properly outside the"addNewPerson" function
A different approach is to store dynamically created persons in an array
class Person {
constructor(fname, lname, birthDate) {
this.firstName = fname;
this.lastName = lname;
this.dov = birthDate;
}
}
let persons = [];
let person1 = new Person("Mark", "Johnson", "12-07-1972");
let person2 = new Person("John", "Miller", "08-17-1923");
persons.push(person1);
persons.push(person2);
function addNewPerson() {
let ffname = prompt("Enter your firstname", "Roger");
let llname = prompt("Enter your lastname", "Doger");
let ddov = prompt("Enter your date of birth", "July 6 2024");
let newPerson = new Person(ffname, llname, ddov);
persons.push(newPerson);
console.log(newPerson);
}
console.log(persons);
console.log(person1);
console.log(person2);