简体   繁体   中英

Javascript calling a function in a function not defined classes

I am calling a method and want to have that method get the value of the returned value of the second method, to be able to use the variable in an element.

I always was able to call a function by putting the function in the other function. It seems when using classes I am unable to achieve this.

Do I have to use a callback method of some sort. I am new to classes.

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();
}

You need to make it clear that you are calling another method of the same class and not a different function by using this :

When you declare a class method without the function keyword, you're basically declaring it as a functional property of the class object. To refer back to the property, you need to put it in the context of the object it's defined in, ie

let dueDays = this.daysLeft(billings);

You must use this , for example if you want to call function inside the class function you must use this to your class knows the reference. So your code should looks like:


  amountByMonth(billings){
     let dueDays = this.daysLeft(billings);

     // Rest of your code
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM