kam*_*myl 12 javascript friend-class typescript
在C++中有一个叫做朋友类的东西.据我所知,TypeScript/JavaScript中没有这样的东西.有没有办法在TypeScript/JavaScript中模拟友元类的这种行为?
举个为什么,什么我尝试做的更好环境(如果需要的话),我做一些小游戏的乐趣(和学习的东西),并尝试做这个.目前我只使用公共方法,一切正常,但我想将这些方法的可访问性限制在另一个类中.我使用TypeScript,如果有帮助的话.
jca*_*alz 18
TypeScript仅提供protected和private访问修饰符.它目前还没有类似的东西friend或internal.
要获得类似的效果:如果要将代码打包为库并.d.ts为其发出声明文件,则可以/** @internal */在不希望外人使用的属性上使用JSDoc批注,同时指定--stripInternal 编译器选项.这将导致导出的声明遗漏这些属性.
另一种做类似事情的方法是提出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;
Run Code Online (Sandbox Code Playgroud)
这很乏味但很明确地说明了代码的哪些部分适用于外部人员而哪些部分不适用于外部人员.
或者,由于以上两者都没有实际阻止人们在运行时访问JavaScript中的私有/内部信息,因此您可以使用IIFE来真正隐藏来自外部人员的内容.但是,在TypeScript中这可能会更烦人,因为它可能需要您创建上述公共接口才能进行类型检查.
所以有一些选择.希望他们帮忙.祝好运!
小智 -12
嗯,当然已经提议了。请参阅https://github.com/Microsoft/TypeScript/issues/2136。
但归根结底,TypeScript 不是 C++,也不是 Java。是的,TypeScript(和 ES6)提供了类,这些类看起来有点像经典 OOP 语言中的类,但该语言并不是真正打算成为具有所有 OOP 花哨功能的成熟 OOP 语言,也不应该是。
如果你发现自己想要友元类,你应该考虑你过度设计你的类层次结构并将过多的设计逻辑放入类结构中的可能性,试图将 JS/TS 变成一种 OOP 语言,而它从来没有打算成为这样的语言。