0

I have a problem with modify variable transfered as function parameter. For example:

function fun() {
   this.a = 1;
   this.b = 2;
   this.show = function() {
      this.increment(this.a);
      this.increment(this.b);
      console.log(this.a); // expected 2
      console.log(this.b); // expected 3
   }
   this.increment = function(elem) {
     elem += 1;
   }
}

var funObj = new fun();
funObj.show();

How can I change this.a and this.b variables in this case?

  • `this.increment(this.a)` will not mutate `this.a`, since JS is always pass by value. – VLAZ Nov 14 '19 at 20:45

3 Answers3

0

When you pass an argument, you pass a copy of what's held in the variable. With primitives, such as numbers, you are passing a copy of that number, so changes to what you pass won't affect the original.

In your case, don't pass the actual data, instead pass a "flag" that determines which of the original data values should be updated.

function fun() {
   this.a = 1;
   this.b = 2;
   this.show = function() {
      // Just pass a "flag" that indicates which property to work with
      this.increment("a");
      this.increment("b");
      console.log(this.a); // expected 2
      console.log(this.b); // expected 3
   }
   this.increment = function(prop) {
      // Check the flag and proceed accordingly
      prop === "a" ? this.a++ : this.b++;
   }
}

var funObj = new fun();
funObj.show();
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
0

I think you're passing in primitives, so they don't retain the change in value. Instead of making a this.increment function, just do it inside the loop.

TedTran2019
  • 887
  • 5
  • 15
0

In your scenario you can simply do this. You don't need to keep a separate function for increment.

function fun() {
   this.a = 1;
   this.b = 2;
   this.show = function() {
      this.a++;
      this.b++;
      console.log(this.a); // expected 2
      console.log(this.b); // expected 3
   }
}

var funObj = new fun();
funObj.show();
Thilina Koggalage
  • 1,044
  • 8
  • 16