简体   繁体   中英

Typescript class no access when private is used

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?

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();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM