3

I have a question about changing the context of "this" keyword in JavaScript. I have the following constructor:

function Obj(name, num)   {
  this.first = first;
  this.num = num;
}

Adding a property:

Obj.prototype.add = testFunc(
   num1, num2,
   function addFunc (x) {
      this.num += x;  }
 );

Then I create a new object:

 var ob = new Obj("Joe", 100);

And call:

 ob.add(50);

testFunc method looks like this:

function testFunc(num1, num2, f)   {
   return function(x, y)   {
   // Perform operations on the Obj object here
   // I tried Obj.apply(this, [f(x, y)]);  with no luck
   }
 }

The problem is that nothing happens in my testFunc method since "this" keyword points to the global object, not the Obj object. I know that in order to change the context of "this" one should use "apply" functionality of JavaScript, but I am just not quite sure how to accomplish this. Thank you for any advise!

1 Answers1

1

If I understand your question correctly, then you can achieve this by means of the following:

function testFunc(num1, num2, f)   {
   return function(x, y)   {
    // f() is called with context of Obj instance, 
    // with args x and y 
    f.call(this, x, y)
   }
 }

function Obj(first, num)   {
  this.first = first;
  this.num = num;
}

Obj.prototype.add = testFunc(
   1, 2,
  function addFunc (x) {
    // addFunc() called from testFunc(), this is
    // instance of Obj
    this.num += x;  
  }
 );
 
  var ob = new Obj("Joe", 100);
  
  console.log('Before', ob.num);
  
  ob.add(50);
  
  console.log('After', ob.num);
  
Dacre Denny
  • 29,664
  • 5
  • 45
  • 65
  • Thank you. Your code works for this particular example. What if I changed the constructor as follows: function Obj(name, num) {this.name = name; } And make num a private variable. Now using ob.add(50) adds 50 twice (any amount that I call, it basically adds twice of this amount). How (if at all) could you modify this code to make it work for both cases? Thank you. – Alexander Nenartovich Oct 23 '18 at 19:55
  • You're welcome - would you be able to post your updated code in a new question and link me to that? If this answer has helped you please consider accepting :-) – Dacre Denny Oct 23 '18 at 20:05
  • Never mind, I figured it out. I'll mark my issue as resolved now to give you credit for your help. Thanks again! – Alexander Nenartovich Oct 23 '18 at 20:12
  • @AlexanderNenartovich ok no problems - you're welcome! – Dacre Denny Oct 23 '18 at 20:13