如果我编写一个创建新人物的函数并将其附加到按钮上的 onClick 事件,我如何访问没有变量名输入的数据?
当用户按下按钮时,出现提示时用户可以输入值,但完成后控制台上没有任何内容打印?
我尝试过的 - 我尝试了以下代码:
<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));
我所期待的 - 单击按钮时,输入提示的值将显示在控制台中。它不是。此代码仅将以下内容打印到控制台:
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 }
动态创建的人员对象未在“addNewPerson”函数之外正确存储或引用
不同的方法
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);