Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);  
  }
  
}
like image 918
a.anev Avatar asked Apr 18 '26 18:04

a.anev


1 Answers

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();
like image 139
Michał Perłakowski Avatar answered Apr 21 '26 07:04

Michał Perłakowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!