在 TypeScript 中,有两种可能的方法来捆绑和公开一组函数。一种是导出一个只包含公共(public)静态函数的类。另一种是创建命名空间,然后从其中导出函数。据我所知,这会在 TypeScript 中产生相同的行为(尽管可能会产生不同的 JavaScript)。是否有一种方法是首选的,或者它是否完全取决于个人偏好。
namespace MyCollection {
export function doSomething(macguffin: any) {
//todo: implement doSomething
}
}
export class MyCollection {
public static doSomething(macguffin: any) {
//todo: implement doSomething
}
}
最佳答案
最好使用模块而不是 namespace 或静态类方法。来自 namespaces and modules 上的 TypeScript 官方文档页面:
Namespaces are simply named JavaScript objects in the global namespace. [...] Just like all global namespace pollution, it can be hard to identify component dependencies, especially in a large application.
[...]
Modules provide for better code reuse, stronger isolation and better tooling support for bundling.
[...]
Starting with ECMAScript 2015, modules are native part of the language, and should be supported by all compliant engine implementations. Thus, for new projects modules would be the recommended code organization mechanism.
关于typescript - 我应该更喜欢命名空间还是带有静态函数的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50415859/