Changing Context of "this" in JavaScript

Viewed 212

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 Answers

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);
  

Related