I have a JavaScript array of objects. Something like this:
var people = [
{ id:1, firstName: 'Joe', lastName: 'Smith' },
{ id:2, firstName: 'Bill', lastName: 'Smith' }
];
I am iterating through the people using forEach
. Here is my code:
function doSomething() {
people.forEach(function(person, self) {
self.helpPerson(person);
}, this);
}
function helpPerson(person) {
alert('Welcome ' + person.firstName);
}
I am trying to call helpPerson
from within the forEach
loop. However, when I attempt to call it, I get an error that says:
TypeError: self.helpPerson is not a function
If I add console.log(self);
, "0" gets printed to the console window. This implies that I'm not passing in my parameter correctly. Or, I'm misunderstanding closures (just when I thought I fully understood it :)).
So, why doesn't self
exit?