barrygrubb barrygrubb - 7 months ago 29
Javascript Question

When calling a function from within another object's for/in loop "Uncaught TypeError: <function name> is not a function" is raised

I have two objects,

Object_1
and
Object_2
.

Object_1:

function Object_1() {
this.object_2Array = [];

for (i = 0; i < 10; i++) {
this.object_2Array[i] = new Object_2();
}
};

Object_1.prototype.functionA = function () {
for (object in this.object_2Array) {
object.functionB();
}
};


Object_2:

function Object_2() {
};

Object_2.prototype.functionB = function () {
console.log("it works");
};


When I call Object_1.functionA() the following is raised:

Uncaught TypeError: object.functionB is not a function


How can I call Object_2.functionB from within a for/in loop of Object_1?

Answer

You are miss using for

for (index in this.object_2Array) {
  this.object_2Array[index].functionB();
 }