在C ++中有一个叫做朋友类的东西。据我所知,TypeScript / JavaScript中没有这样的东西。有没有办法在TypeScript / JavaScript中模拟友元类的这种行为?
为了给出更好的背景(如果需要)我尝试做的事情,我做了一些小游戏以获得乐趣(并学习东西)并尝试this。目前我只使用公共方法,一切正常,但我想将这些方法的可访问性限制在另一个类中。我使用TypeScript,如果有帮助的话。
答案 0 :(得分:14)
TypeScript仅提供protected
and private
访问修饰符。它目前不具有friend
或internal
。
要获得类似的效果:如果您将代码打包为库并为其发出.d.ts
声明文件,则可以在不希望外人使用的属性上使用/** @internal */
JSDoc注释使用,并指定--stripInternal
compiler option。这将导致导出的声明遗漏这些属性。
另一种做类似事情的方法是提出你的类实现的公共interface
,然后只将类导出为公共接口。例如:
// public interfaces
export interface UnitStatic {
new(grid: Grid, x: number, y: number): Unit;
}
export interface Unit {
move(x: number, y: number): void;
}
export interface GridStatic {
new(): Grid;
NUM_CELLS: number;
CELL_SIZE: number;
}
export interface Grid {
// public methods on Grid
}
// private implementations
class UnitImpl implements Unit {
constructor(private grid: GridImpl, private x: number, private y: number) {
}
move(x: number, y: number) {
// ...
}
}
class GridImpl implements Grid {
cells: Unit[][] = [];
constructor() {
// ...
}
static NUM_CELLS = 10;
static CELL_SIZE = 20;
}
//public exports
export const Unit: UnitStatic = UnitImpl;
export const Grid: GridStatic = GridImpl;
这很乏味但是非常清楚地表明你的代码的哪些部分是针对外人的,哪些不是。
或者,由于以上两者都没有实际阻止人们在运行时访问JavaScript中的私人/内部信息,因此您可以使用IIFE 隐藏来自外人的内容。但是,这在TypeScript中可能会更烦人,因为它可能需要您创建上述公共接口才能进行类型的检查。
所以有一些选择。希望他们帮忙。祝你好运!
答案 1 :(得分:-3)
嗯,当然有人建议了。请参阅https://github.com/Microsoft/TypeScript/issues/2136。
但最终,TypeScript不是C ++,也不是Java。是的,TypeScript(和ES6)提供了类,它们看起来像是经典OOP语言中的类,但是这种语言实际上并不是一个完整的OOP语言,具有所有OOP的铃声和口哨声,也不应该如此。
如果您发现自己想要朋友类,您应该考虑过度设计类层次结构并将过多的设计逻辑放入类结构中的可能性,尝试将JS / TS转换为OOP语言打算成为。