I’m starting to play around a bit with OOP in JavaScript and I have an array of simple objects that I’m trying to loop over and call a method on each, however, when I run this under Google Chrome, I get the following exception in the JavaScript debugger:
Uncaught TypeError: Object 0 has no method 'drawHisto'
Simplified code snippet below:
var histograms = [];
var h1 = null;
var h2 = null;
var h3 = null;
function Init() {
h1 = new Histogram(canvas1, "red");
h2 = new Histogram(canvas2, "blue");
h3 = new Histogram(canvas3, "green");
histograms = [ h1, h2, h3];
}
function Histogram(canvas, color) {
// this is my constructor
}
Histogram.prototype.drawHisto = function() {
// I will add code here to draw the histogram
}
function DrawHistograms() {
for (var h in histograms) {
h.drawHisto(); // Throws exception!
}
// h1.drawHisto() <--- this works
}
Any idea what I might be doing wrong? I’ve simplified the code here a bit, so if you find that the problem must be elsewhere, I can add additional context.
Thank you.
A
for inloop in JavaScript does not iterate over an array’s values, but rather over an object’s keys. Simply use aforloop as usual:Or, if compatibility with Internet Explorer 8 and earlier is no issue, you may be able to use
Array.forEach: