0

I have some code that looks like this:

export class Viewer {

  private scene = new Scene(); 

}

Then when I import it as try:

const viewer = new Viewer();

then if I try:

viewer.scene it is now available unless I change:

private scene = new Scene(); 

TO

public scene = new Scene();

My question is:

How can I access the property without changing private to public?

13
  • 6
    What do you think the word "private" is supposed to mean here? Commented Jul 26, 2018 at 20:15
  • 4
    Isn't the idea of private to keep the property private? Commented Jul 26, 2018 at 20:15
  • 3
    Why though? If it should be public, make it public? Commented Jul 26, 2018 at 20:16
  • 4
    If the act of making something public was inherently bad practice, it wouldn't exist. It's the context of how you use certain methodologies that make them bad practice - not the methodologies themselves. Commented Jul 26, 2018 at 20:17
  • 3
    If you need to read the value, have you looked into getters? typescriptlang.org/docs/handbook/classes.html#accessors Commented Jul 26, 2018 at 20:19

1 Answer 1

1

Although you don't state this explicitly in the question, my guess is you want to partially restrict access to the member, for example if you want to allow reading the field from the outside but not writing it and you only need to set it once, you can use the read-only modifier

export class Viewer {

  private readonly scene = new Scene(); 

}

Another option is to use properties and creeate just a public getter for a private field

export class Viewer {
  get scene(): Scene {
    return this._scene;
  }

  private _scene = new Scene();

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.