Please help me understand "this"

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

I don’t really.like the code because it’s a little bit confusing, but:

this is what is to the left of the period (.) when a function is called. It is the calling context

function example() {
  console.log(this);
}

JavaScript uses objects for everything. So if you paste the above function into your browser console and run it, it will execute in the global scope. Which is an object called window. Which means you can think of the above function like:

window.example = function () {
  console.log(this)
}

window is to the left of the period, it will log the object window.

A constructor is a function for creating instances of an object, to which you can attach functions (class syntax wraps all that up into one structure, it’s there to make it consistent to write).

this in the constructor and the functions attached to it, when you run new Calculator(), is going to be the instance of newly constructed Calculator object. So if you do for example:

const myCalculator = new Calculator(el1, el2);

This builds the brand new object. It runs the constructor function, which assigns the two arguments, so you have:

{
  currentOperandTextElement: whateverEl1is,
  previousOperandTextElement: whateverEl2is,
}

And then runs myCalculator.clear() (this is what I mean by the code being confusing), which sets three more properties:

{
  currentOperandTextElement: whateverEl1is,
  previousOperandTextElement: whateverEl2is,
  currentOperand: "",
  previousOperand: "",
  operation: undefined,
}

Then the myCalculator object is ready: it has a set of functions attached to it for you to use, and it has some properties that you manipulate using those functions.

Edit: This is all a slight simplification because there are a lot of edge cases where this doesn’t refer to what you first expect it to. What this refers to is decided when that specific part of the code it’s referenced in actually runs, which can cause quite a bit of confusion. Left of the dot is IMO a fairly good rule of thumb though, as long as you remember that it’s what is to the left of the dot when a function/method is ran, not necessarily whereabouts it is in your code.

2 Likes

Yeah I pretty much understood the this.
Can you please explain how the properties of one function can be used by other function
for example:

clear(){
        this.currentOperand = "";
        this.previousOperand = "";
        this.operation = undefined;
    }

How can currentOperand declared in clear() be used by updateDisplay() function? Doesn’t the context matter for

updateDisplay(){
        this.currentOperandTextElement.innerHTML = this.currentOperand
    }

They are not properties of a function, they are properties of the class. A class property can be accessed in any method of the class. They are basically the equivalent of global variables for the class.

1 Like

This cleared up many queries. Thanks

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.