Add 2 numbers of the same object

when the numbers add up i got with the s1 = 40
and with s2 = 10, but this is not what i want i dont know why it does this, it only adds up correctly if i put the same number in it like example

s1.add(50);
s1.add(50);

then it does work. but for the rest not

<script>
    
    function Summer(){
        this.add = function(getal){
            this.NewGetal = getal;
        }
            
            this.getCurrentSum = function(){
                this.som = this.NewGetal + this.NewGetal;
                return this.som;
            }
    }
    
    var s1 = new Summer();
    var s2 = new Summer();

    s1.add(10);
    s1.add(20);
    
    s2.add(30);
    s2.add(5);

    
    // prints 30
    console.log(s1.getCurrentSum());
    
    // prints 35
    console.log(s2.getCurrentSum());

Your add() method doesn’t actually add anything, it just sets NewGetal to a new value; only when calling getCurrentSum() a summation takes place, but not to the current sum but it doubles the current NewGetal value. This would give you the expected results:

function Summer () {
  this.sum = 0

  this.add = function (value) {
    this.sum += value
  }

  this.getCurrentSum = function () {
    return this.sum
  }
}

thanks for the response, i appreciate it

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