2

I defined this class in JavaScript:

function Signal(lbl, ho, tag) {
    this.lbl = lbl;
    this.ho = ho;
    this.tag = tag;
    this.getstatus = function () {
        if (this.ho) {
            $.get('/get.cgi?' + this.tag + '=?0', function (data) {
                console.log(data);
                setTimeout(this.getstatus, 1000);
            });
        }
    };
}

Once getstatus is called, it should start calling itself with setTimout, but it doesn't! It only works one time.

If I use a function without a class, it works!

Please help me out.

Thanks!

Fabian Fagerholm
  • 4,099
  • 1
  • 35
  • 45
xgon
  • 175
  • 1
  • 3
  • 11

1 Answers1

3

The problem is when getStatus is invoked by the timer, this inside the method does not refer to the object, you can pass a custom value for this using bind(). Also note that in the ajax callback this refers to the ajax settings object.

function Signal(lbl, ho, tag) {
    this.lbl = lbl;
    this.ho = ho;
    this.tag = tag;
    this.getstatus = function () {
        if (this.ho) {
            var signal = this;
            $.get('/get.cgi?' + this.tag + '=?0', function (data) {
                console.log(data);
                setTimeout(signal.getstatus.bind(signal), 1000);
            });
        }
    };
}
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • 1
    I like to use a more expressive name than "self" (or "that"), in this case, *signal* seems appropriate so `var signal = this` and `signal.getstatus.bind(signal)` so it's clear what the bound *this* is. The correct *thisArg* can also be set using `setTimeout(function(){signal.getstatus()},1000)`. – RobG Mar 09 '16 at 04:47
  • @RobG: `signal` could be *any* Signal. `self` does (by convention) mean the current instance. Usually code is not misty enough that it's unclear which (of multiple instances) is meant. – Bergi Mar 09 '16 at 04:57
  • @Bergi—similarly, *self* could be anything, the use of *signal* (or whatever *this* is an instance of) just gives a hint as to what it is. *self* might be appropriate for a method that might be called with different "classes" of objects at *this*. – RobG Mar 09 '16 at 09:20
  • I used thisSignal.... – xgon Mar 10 '16 at 02:20