logic problem when instantiating Javascript class

2

I'm starting with Javascript and POO , but when creating this class and writing the command to print in console, it only shows me the content of the object:

(ƒ operacion(){
    return this.n1+this.n2;
})

What prevents me from receiving the numbers I enter the constructor and prints the result? Thank you! : D Code;

class sumatoria{
    numero (n1,n2){
        this.n1=n1;
        this.n2=n2;
    }

    get resultado(){
        return this.operacion
    }

    operacion(){
        return this.n1+this.n2;
    }
}

var suma= new sumatoria(2+2);
console.log(suma.resultado);
    
asked by Ketchup786 21.09.2018 в 20:55
source

1 answer

3

I made some changes:

  • A class must have a constructor.
  • console.log(suma.resultado()); instead of console.log(suma.resultado); since the result is a method.
  • class sumatoria{
        constructor (n1,n2){
            this.n1=n1;
            this.n2=n2;
        }
    
        get resultado(){
            return this.operacion
        }
    
        operacion(){
            return this.n1+this.n2;
        }
    }
    
    var suma= new sumatoria(2,2);
    console.log(suma.resultado());
        
    answered by 21.09.2018 / 20:59
    source