JS - Hiding Class Properties

I know that there’s a difference between Scope and Closure and by using Closure I could hide properties and methods of a class/object in JS. But I don’t understand Closure very well. For example, in the code below:

class Printer {
  constructor(){
    this.x = 10;
    this.output();
  }

  output() {
    console.log(this.x);
  }
}
const print = new Printer();

How could I hide the x property and make it accessible to the output method without passing x as param? Thanks in advance.

That can’t be done with classes.

Hum. So probably I should go Object Factory way? instead of using Classes? I’ll try that.

ps. Not the same, but interesting using Get/Set:

class Printer {
  constructor(){
    let number = 10;

    Object.defineProperty(this, 'number', {
      get: function(){
        return number;
      }
    })
  }
}
const print = new Printer();
console.log(print.number);

And I could also use Set and throw an Error in case someone attempt to set a value!?!?
But I think someone should do that just for critical situations or always as a good design and coding principles?

The title of this thread is about hiding class properties. But it seems with what you’ve done there that a person needs to know about the number property, to use it with print.number

Isn’t there a conflict there?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.