Reputation: 349
I have a "class" with properties and methods. And I have instances of that class in an array in some other place in the code. Now I want to iterate through all of them and for each call a method. Something like this:
arr.forEach(draw());
But of course it looks up a global function draw() which is not there. How do I access object's methods in this situation?
I am new to javascript, so I assume it might be a stupid question, but I can't find an answer for some reason.
Upvotes: 0
Views: 148
Reputation: 204
here is the documentation of the forEach function https://msdn.microsoft.com/library/ff679980(v=vs.94).aspx
forEach first parameter is an callback function... that function receives 3 parameters, the first one is each object in that array.
arr.forEach(function(element){
draw()
});
Where element is the object you want to access.
Upvotes: 1
Reputation: 532595
forEach takes a callback that accepts 3 arguments, the array element, the index, and the array. You only need the first. Wrap your call to draw()
in an anonymous function and invoke it on the element from the function call.
arr.forEach(function(elem) { elem.draw(); });
Upvotes: 2