1

I want to use "destructuring assignment" inside of a class function to get ride of using "this" keyword multiple time...

but i got this error:

Uncaught ReferenceError: a is not defined

my code is somthing like this:

class className {
        constructor() {
                this.a = 1;
                this.b = 2;
                this.c = 3;
        }
        function() {
                [a, b, c] = [this.a, this.b, this.c];
        }
}

let obj = new className;
obj.function();

(my purpose is to fill a 10*10 array with a, b and c so I prefer to use a instead of this.a)

Amin Sanei
  • 39
  • 6
  • 3
    You forgot to declare the variables. Use `const`. – Sebastian Simon Jan 14 '23 at 19:37
  • 2
    `const [a, b, c] = [this.a, this.b, this.c];` – Konrad Jan 14 '23 at 19:38
  • It works, thank you, but why outside of a class it is not necessary to declare variables? – Amin Sanei Jan 14 '23 at 19:40
  • 2
    @AminSanei Because a class body is strict by default. I strongly encourage you to move to [JavaScript modules](//developer.mozilla.org/en/docs/Web/JavaScript/Guide/Modules) or at least enable [strict mode](//developer.mozilla.org/en/docs/Web/JavaScript/Reference/Strict_mode) everywhere. – Sebastian Simon Jan 14 '23 at 19:41

0 Answers0