3

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
}
James Stott
  • 129
  • 1
  • 7
  • Just a guess: if you omit the proper declaration of the variable it automatically creates a *global* variable for you. That probably does not work in class context thus the variable is just not defined at all then. To your last question: if you use `let` or `const` the variable is block scoped thus belongs into the for {} block scope. If you use var it is function level scoped so its available *after* the loop. – Xatenev Feb 21 '19 at 11:57
  • Oh you're right - I didn't realise that. I've been running for...of loops that are polluting the global space I suppose. Thanks for the insight. – James Stott Feb 21 '19 at 11:59
  • You will also need to bind your methods, other 'this' inside your methods will point at your methods and not your class. – philipjc Feb 21 '19 at 12:15

1 Answers1

2

Class is ES6 feature and that mendate declaration of variable before using it.The same behaviour you can achieve with "strict mode". But when you declare it as a independent function then JS engine doesn't impose "strict mode" rules on you function unless you declare "strict mode" by yourself at the start of the script.

RK_15
  • 929
  • 5
  • 11