a.anev
a.anev

Reputation: 135

Making a es6 variable global in a class

What I'm trying to do is make a variable which I can use across different functions in the class. But for some reason whenever I write let variable above the constructor I get 'Unexpected token. A constructor, method, accessor, or property was expected.

Tried it with a var and I pretty much get the same result

class ClassName {

  let variable;

  constructor() {
    variable = 1;  
  }
  
  function() {
    console.log(variable + 1);  
  }
  
}

Upvotes: 2

Views: 11647

Answers (1)

Michał Perłakowski
Michał Perłakowski

Reputation: 92521

You should access the variable as a property of this:

class ClassName {
  constructor() {
    this.variable = 1;  
  }
  someOtherFunction() {
    console.log(this.variable + 1); // 2
  }
}

new ClassName().someOtherFunction();

Upvotes: 9

Related Questions