How to use function in class methods?

I have a calculator class. and this has following methods, getInputFields and sum.

const addBtn: HTMLButtonElement = document.getElementById("add") as HTMLButtonElement;;
const subBtn: HTMLButtonElement = document.getElementById("subtract") as HTMLButtonElement;
const multiplyBtn: HTMLButtonElement = document.getElementById("multiply") as HTMLButtonElement;
const divideBtn: HTMLButtonElement = document.getElementById("divide") as HTMLButtonElement;

class Calculator {

    result: HTMLSpanElement;
    inputOne: HTMLInputElement;
    inputTwo: HTMLInputElement;
    numOne:number;
    numTwo:number;

    constructor() {
        this.result = document.getElementById("result") as HTMLSpanElement;
        this.inputOne = document.getElementById("num1") as HTMLInputElement;
        this.inputTwo = document.getElementById("num2") as HTMLInputElement;
    }

    getInputFields() {
        this.inputOne = document.getElementById("num1") as HTMLInputElement;
        this.inputTwo = document.getElementById("num2") as HTMLInputElement;
        this.numOne = parseInt(this.inputOne.value);
        this.numTwo = parseInt(this.inputTwo.value);
    }

    sum() {
        this.getInputFields();
        if (!isNaN(this.numOne) && !isNaN(this.numTwo)) {
            this.result.textContent = (this.numOne + this.numTwo).toString();
        }
    }

Below the above code, I use addEventListener to run sum method.

const calculator = new Calculator();
addBtn.addEventListener('click', calculator.sum);

You can see this.getInputFields is inside sum() method. Why do I have that inside sum method?
Because I want to make subtract, multiplication, division methods.
But I don’t want to repeat the same codes to assign document.getElmentById("num1") as HTMLInputElement in every method.

That’s why I put that code into getInputFields.
But this doesn’t work inside class methods..

Here’s error I got,

main.js:20 Uncaught TypeError: this.getInputFields is not a function
    at HTMLButtonElement.Calculator.sum (main.js:20)

2 thoughts on “How to use function in class methods?”

Leave a Comment