I have a class
class People {
constructor(people) {
this.people = people;
}
someMethod () {
for (person of this.people) {
console.log(person);
}
}
}
But if I run this code:
let people = new People(['James']);
people.someMethod();
I get the following error:
ReferenceError: person is not defined
If I change my someMethod()
implementation to explicitly declare person
;
for (let person of this.people)
It works. Now, if I created this not as a method of a class but as a function, I would not need to do this explicit declaration of person
.
What is the reason for this? Are there any other instances where this behaviour can be observed? Is it therefore recommended to always initiate temporary variables in loops explicitly?
One final question when I declare a variable in a for...of
loop, does the variable belong to the scope that the for loop sits inside or in the scope of the for loop?
// is 'a' scoped here
for (let a of A) {
// or is 'a' scoped here
}