我正在调用一个方法,并希望该方法获取第二个方法的返回值,以便能够在元素中使用该变量。
我总是能够通过将函数放入另一个函数中来调用该函数。看来在使用类时我无法实现这一点。
我是否必须使用某种回调方法?我是新来的。
class Bills{
constructor(amount,payment,duedate,apr){
this.amount = amount;
this.payment = payment;
this.duedate = duedate;
this.total = total;
this.apr = apr;
}
amountByMonth(billings){
//This is the function I am calling inside the function to get the value of.
let dueDays = daysLeft(billings);
const items = document.getElementById('bills');
const newitem = document.createElement('ul');
newitem.innerHTML = `
<li>Monthly Amount Due :${billings.amount}</li>
<li>Monthly Amount Due :${dueDays}</li>
<li>Total On Card: ${billings.total}</li>`;
items.appendChild(newitem);
}
daysLeft(billings){
let date1 = new Date();
let dueDate = new Date(billings.duedate);
let timeDiff = Math.abs(dueDate.getTime() - date1.getTime());
let diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
console.log(diffDays);
return diffDays;
}
}// end
document.getElementById('subBtn').addEventListener('click',valueinput);
function valueinput(e){
let amount = document.getElementById('payment').value;
let total = document.getElementById('total').value;
let duedate = document.getElementById('dues').value;
let billings = new Bills();
billings.amount = amount;
billings.duedate = duedate;
billings.total = total;
billings.daysLeft(billings);
billings.amountByMonth(billings);
e.preventDefault();
}
最佳答案
您需要清楚地表明您正在使用 this
调用同一类的另一个方法,而不是不同的函数:
当您声明不带 function 关键字的类方法时,您基本上将其声明为类对象的函数属性。要引用该属性,您需要将其放在定义它的对象的上下文中,即
let dueDays = this.daysLeft(billings);
关于Javascript 在未定义类的函数中调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56281558/