1

I usually program in Java and when I add an event listener to an attribute in a class, I can call the methods from the class inisde the event. However in JavaScript if I use "this." inside the function, the context is "onclick" and if I don't use "this." I get an error that resetear is not defined. How can I access the attributes and methods from Calculadora inside the onclickfunction?

class Calculadora{
    constructor () {
        this.resultado = document.getElementById("resultado");
        this.c = document.getElementById("C");
        ...

        this.memoria = "";
        this.a = 0;
        this.b = 0;
        this.operacion = "";
    }

    resetear(){
        this.resultado.textContent = "";
        this.a = 0;
        this.b = 0;
        this.operacion = "";
    }

    assignar() {
        this.c.onclick = function(e){ // Here I need to change some things about Calculadora
            resultado.textContent = "";
            this.a = 0;
            this.b = 0;
            this.operacion = "";
        }
        ...
    }
}

2 Answers2

2

You can define the onclick handler using an arrow function:

this.c.onclick = e => {

}

Doing this way, this inside the handler is the class itself.

Arrow functions preserves the scope of this while function creates a new scope.

ema
  • 5,668
  • 1
  • 25
  • 31
2

You could use the ES6 Arrow Function:

class Calculadora{
    constructor () {
        this.resultado = document.getElementById("resultado");
        this.c = document.getElementById("C");
        ...

        this.memoria = "";
        this.a = 0;
        this.b = 0;
        this.operacion = "";
    }

    resetear = () => {
        this.resultado.textContent = "";
        this.a = 0;
        this.b = 0;
        this.operacion = "";
    }

    assignar = () => {
        this.c.onclick = e => {
            resultado.textContent = "";
            this.a = 0;
            this.b = 0;
            this.operacion = "";
        }
        ...
    }
}

Arrow functions pass the context of the outside scope (the scope they're defined in) into the function. Read more about arrow functions here.

Sagi Rika
  • 2,839
  • 1
  • 12
  • 32