0

I have a basic class like so:

class Something
{
    constructor() {
        this.something = 0;
    }

    increaseSomething(incr = 1) {
        this.something += incr;
    }
}

However, right now I can simply do new Something().something += 100

Is there any way to keep something attribute as protected? I want increaseSomething to be my public setter.

Ps. I know it can be done with functions but I want to do it with ES6 classes.

Aris
  • 2,978
  • 5
  • 22
  • 31
  • 1
    ES6 classes are just syntactic sugar over regular Javascript objects. Javascript doesn't have any notion of access modifiers. You can simulate something like it with closures, but it completely breaks prototypical inheritance. Use a naming convention like `_something` to signal "protected" to your fellow developers, or use something like TypeScript which can somewhat enforce this during compilation. – deceze Aug 31 '16 at 08:43
  • @deceze I'll have a look at typescript, as I need type safety, return annotations and all the features from other OO oriented languages. – Aris Aug 31 '16 at 10:10

0 Answers0