简体   繁体   English

在未定义的函数类中调用函数的Javascript

[英]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 : 你需要说清楚,你所呼叫的同一类的另一种方法,通过使用不是一个不同的功能this

When you declare a class method without the function keyword, you're basically declaring it as a functional property of the class object. 当声明不带function关键字的类方法时,基本上就是在将其声明为class对象的功能属性。 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. 您必须使用this ,例如,如果要在类函数内部调用函数,则必须使用this函数使类知道引用。 So your code should looks like: 因此,您的代码应如下所示:


  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