0

I have created class like below. Is there something wrong with following? I just followed others' way but it continuously gives me, 'Test run failure: file script.js has invalid syntax​​'. I have searched very hard, I do not think there is any exceptions from them. Could you give some advice for this?

class AAA {
   constructor(value) {
     this.value = value;
   }

   add = a => value + a;
}
Anna Lee
  • 909
  • 1
  • 17
  • 37
  • You can't have assignments inside the class body. What's wrong with the method syntax: `add(a) { return this.value + a; }`? The arrow function won't work anyway, because you need `this` to access the `value`, which arrow functions can't do. – ibrahim mahrir Oct 16 '18 at 23:09
  • You can’t do this yet without a transpiler. – evolutionxbox Oct 16 '18 at 23:25
  • Thank you so much for your answers. I just changed into regular function definition. It looked like React component uses that way. :) – Anna Lee Oct 17 '18 at 19:23

1 Answers1

0

You cannot assign in the class body. You can do it in the constructor or you could use TypeScript.

class AAA {
   constructor(value) {
     this.value = value;
     
     this.add = a => this.value + a;
   }
}


let aaa = new AAA(5);

console.log(aaa.add(5));
Adrian Brand
  • 20,384
  • 4
  • 39
  • 60