Javascript 使用private时,Typescript类没有访问权限
我有一些代码如下所示:Javascript 使用private时,Typescript类没有访问权限,javascript,typescript,ecmascript-6,Javascript,Typescript,Ecmascript 6,我有一些代码如下所示: export class Viewer { private scene = new Scene(); } 然后,当我将其作为try导入时: const viewer = new Viewer(); 如果我尝试: viewer.scene现在可用,除非我更改: private scene = new Scene(); 到 我的问题是: 如何在不将private更改为public的情况下访问属性?虽然您在问题中没有明确说明这一点,但我猜您希望部分限制对成员的
export class Viewer {
private scene = new Scene();
}
然后,当我将其作为try导入时:
const viewer = new Viewer();
如果我尝试:
viewer.scene现在可用,除非我更改:
private scene = new Scene();
到
我的问题是:
如何在不将private更改为public的情况下访问属性?虽然您在问题中没有明确说明这一点,但我猜您希望部分限制对成员的访问,例如,如果您希望允许从外部读取字段但不写入字段,并且只需设置一次,您可以使用只读修改器
export class Viewer {
private readonly scene = new Scene();
}
另一种选择是使用属性和create作为私有字段的公共getter
export class Viewer {
get scene(): Scene {
return this._scene;
}
private _scene = new Scene();
}
你认为“私有”这个词在这里应该是什么意思?私有的概念不是让财产保持私有吗?为什么?如果应该公开,就公开?如果公开的行为本质上是一种不良行为,那么它就不存在了。这是你如何使用某些方法使它们成为不好的实践的背景,而不是方法本身。如果你需要阅读价值,你有没有研究过getter?
export class Viewer {
get scene(): Scene {
return this._scene;
}
private _scene = new Scene();
}