I am coding a calculator project but can’t seem to wrap me head around the “this.” in code.
class Calculator{
constructor(currentOperandTextElement, previousOperandTextElement){
this.currentOperandTextElement = currentOperandTextElement;
this.previousOperandTextElement = previousOperandTextElement;
this.clear()
}
In clear() method - which is a part of calculator class - why are we using “this” keyword. I ran the code without "this " and it didn’t broke down.
2nd question
How am I creating a variable (currentOperand , previousOperand and operation) without using var?
Is this because its’s actually a key value pair and not a variable ?
How “currentOperand” is being passed from one method to an other?
clear(){
this.currentOperand = "";
this.previousOperand = "";
this.operation = undefined;
}
appendNumber(number){
this.currentOperand = number;
}
choseOperation(operation){
this.currentOperand = operation;
}
updateDisplay(){
this.currentOperandTextElement.innerHTML = this.currentOperand
}
compute(){
}
delete(){
}
}
const numbersButton = document.querySelectorAll("[data-number]");
const operationsButton =document.querySelectorAll("[data-operation]");
const equalsButton = document.querySelector("[data-equals]");
const deleteButton = document.querySelector("[data-delete]");
const allClearButton = document.querySelector("[data-all-clear]")
const previousOperandTextElement = document.querySelector("[data-previous-operand]");
const currentOperandTextElement = document.querySelector("[data-current-operand]");
// Instanciating
const calculator = new Calculator(currentOperandTextElement, previousOperandTextElement);
numbersButton.forEach(button =>{
button.addEventListener("click", ()=>{
calculator.appendNumber(button.innerHTML);
calculator.updateDisplay();
})
})
operationsButton.forEach(button =>{
button.addEventListener("click", ()=>{
calculator.choseOperation(button.innerHTML);
calculator.updateDisplay();
} )
})
allClearButton.addEventListener("click", ()=>{
calculator.clear();
calculator.updateDisplay();
})