0

Below is my problem code:

var counter = new Counter();
counter.Load("20141211");

--

Counter = function () {
    this.Counters = new Array();
    this.Load = function (date) {
        $.getJSON("http://url", { "Date": date }, function (Count) {
            if (!Count.Error) {
                this.Counters[this.Counters.length] = Count;
            }
        });
    }
}

The line this.Counters[this.Counters.length] = Count; is where this.Counters is undefined and I don't understand why as it is defined above.

I would think it got defined when I call new Counter(), so it can be used later when I call counter.Load(). But it is simply undefined.

If I where to create this as a linear code it would work:

var Counters = new Array();
Counters[Counters.length] = Count;
Espen
  • 3,607
  • 11
  • 48
  • 75

3 Answers3

4

Because scope!

Within the callback of $.getJSON, this no longer refers to the instance of your object. The easiest way round this is to use another variable (often self) to refer to the instance, and use this inside your callback:

Counter = function () {
    var self = this;
    self.Counters = new Array();
    self.Load = function (date) {
        $.getJSON("http://url", { "Date": date }, function (Count) {
            if (!Count.Error) {
                self.Counters[self.Counters.length] = Count;
            }
        });
    }
}
Jamiec
  • 133,658
  • 13
  • 134
  • 193
2

The value of this changes when you're in the .getJSON callback. So save the value of this under a different variable name and use that value when you're in the callback.

sahbeewah
  • 2,690
  • 1
  • 12
  • 18
1

Because you lost context. Add var self = this; in top of constructor, and into callback use self.Counters[self.Counters.length] = Count;

Counter = function () {
    var self = this;
    this.Counters = new Array();
    this.Load = function (date) {
        $.getJSON("http://url", { "Date": date }, function (Count) {
            if (!Count.Error) {
                self.Counters[self.Counters.length] = Count;
            }
        });
    }
}
ndugger
  • 7,373
  • 5
  • 31
  • 42