簡體   English   中英

在未定義的函數類中調用函數的Javascript

[英]Javascript calling a function in a function not defined 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();
}

你需要說清楚,你所呼叫的同一類的另一種方法,通過使用不是一個不同的功能this

當聲明不帶function關鍵字的類方法時,基本上就是在將其聲明為class對象的功能屬性。 要引用該屬性,您需要將其放在其定義的對象的上下文中,即

let dueDays = this.daysLeft(billings);

您必須使用this ,例如,如果要在類函數內部調用函數,則必須使用this函數使類知道引用。 因此,您的代碼應如下所示:


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

     // Rest of your code
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM