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?