0

My question is about arrays contained in Javascript objects:

My program has many objects that want to be "pulsed" by the window. Rather than do a setInterval in each of them, I just create a single object that traverses an array of objects, or "clients" and pulses each of them - each must implement a method named "pulse" - standard publish and subscribe/listener pattern stuff.

Here is the code that works:

var clients = [];

function Power() {}

Power.prototype.plugIn = function (someObject) {
    clients[clients.length] = someObject;
    if (!this.interval) {
        this.interval = setInterval(this.pulseClients, 13);
    }
};

Power.prototype.pulseClients = function () {
    var i;
    for (i = 0; i < clients.length; i += 1) {
         clients[i].pulse();
    }
};

Notice that I have to define the array, clients, OUTSIDE of my object. For encapsulation, I would prefer this:

function Power() {
    this.clients = [];
}

Power.prototype.plugIn = function (someObject) {
     this.clients[this.clients.length] = someObject;
     if (!this.interval) {
        this.interval = setInterval(this.pulseClients, 13);
    }
};

Power.prototype.pulseClients = function () {
    var i;
    for (i = 0; i < this.clients.length; i += 1) {
         this.clients[i].pulse();
    }
};

When I do this, however, my client objects don't get pulsed. Syntactically, it seems to be consistent with examples of arrays in objects I've seen online. The firefox debugger indicates that this.clients is undefined, and my this variable no longer refers to the Power object, but to the Window object when I do this. Am I missing something obvious?

  • 1
    Two problems: **1.** inside `Power`, it should be `this.clients = [];` not `clients = [];`. **2.** `this` get messed up by `setInterval` – ibrahim mahrir Dec 05 '17 at 04:46
  • https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback – epascarello Dec 05 '17 at 04:50
  • Possible duplicate of [Javascript setInterval and \`this\` solution](https://stackoverflow.com/questions/2749244/javascript-setinterval-and-this-solution) – ibrahim mahrir Dec 05 '17 at 04:54
  • yeah, I omitted that this when typing it in here - it was in my code - code still doesn't work and if 2 is the culpirit, why does my working code work? – user3721389 Dec 05 '17 at 04:55
  • @user3721389 because `this` inside `Power.prototype.pulseClients` will be `window`, not the instance of `Power`. So `this.clients` is `window.clients` which is `undefined`. – ibrahim mahrir Dec 05 '17 at 05:00
  • @user3721389 Try changing to this: `this.interval = setInterval(this.pulseClients.bind(this), 13);` or `this.interval = setInterval(() => this.pulseClients, 13);` – ibrahim mahrir Dec 05 '17 at 05:01
  • Ah! Thanks ibrahim, that worked! – user3721389 Dec 05 '17 at 05:17

0 Answers0