Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Nested Functions Scope

Tags:

javascript

I have the following javascript object, somewhat pseudocode:

{
  dateField: new Date(),
  addMinutes:function(numMinutes)
  {
     CallWebService(numMinutes, function{alert(this.dateField; });
  }
}

The problem is the scope of the callback function in CallWebService doesn't see the dateField property of the object. Is there a way I can access it? Thanks!

like image 870
extnoob Avatar asked Feb 26 '23 17:02

extnoob


1 Answers

You need to preserve the context (the this value) of the addMinutes function.

There are several ways to achieve it, the most easy one is to simply store a reference of this on a variable, that variable will be available to the scope of the callback function, e.g.:

var obj = {
  dateField: new Date(),
  addMinutes: function(numMinutes) {
     var instance = this;
     CallWebService(numMinutes, function () {
       alert(instance.dateField);
     });
  }
};
like image 74
Christian C. Salvadó Avatar answered Mar 11 '23 10:03

Christian C. Salvadó