学习型脚本-- 最后创建emp对象,但是需要传入inputData函数来打印表单数据。
类 empdata { 公共 empid : 数字;公共 empname : 字符串;公共工作:字符串;公众号:号码;
constructor (empid : number, empname : string, job : string, leaves : number){
this.empid = empid; this.empName= empName; this.job=job; this.leaves=leaves; }
inputData(){
console.log(this.empname);
console.log(this.job);
console.log(this.leaves);
}
getFormData (){
const form: HTMLFormElement = document.querySelector('#myform')!;
form.onsubmit = () => {
const formData = new FormData(form);
const empName = formData.get('emp') as string;
const job = formData.get('job') as string;
const leaves = formData.get('leaves') as string;
return false; // prevent reload }; } } let emp = new empdata(1,"srikanth","manager",10); emp.getFormData();
emp.inputData();
答案 0 :(得分:1)
您定义了一个函数但没有调用它。您可以在类中保留您的定义(不是特别在构造函数中),您可以在创建对象后调用它,例如:
constructor(...)
{
this.inputData();
}
inputData()
{
console.log(this.empname);
console.log(this.job);
console.log(this.leaves);
}
//After your object creation
this.inputData(); // call again
更新: 根据注释,如果您希望在对象创建期间和 formdata 值更改期间更新值,您可以使用相同的函数 inputData() 来实现:
constructor(){
this.empid = empid;
this.inputData(empName, job, leaves);
}
inputData(empName, job, leaves){
this.empName= empName;
this.job=job;
this.leaves=leaves;
console.log(this.empname);
console.log(this.job);
console.log(this.leaves);
}
// Afer updating form:
this.inputData(empName, job, leaves);