我正在写一些类型脚本类,这一点有问题
// BasePlugin.ts
export abstract class Base {
protected abstract readonly commands: string[];
}
// Loader.ts
export const plugins: Base[] = [...] // A lot of plugins that extend Base that are already instantiated
// Help.ts
import { plugins } from './Loader'
export default class Help extends Base {
commands = [
'$help => sends this message'
];
getAllHelp(): void {
plugins.forEach(plugin => {
plugin.commands.forEach(command => {
...
)};
)};
...
}
}
我在
plugin.command
处遇到错误,并显示错误消息[ts] Property 'commands' is protected and only accessible through an
instance of class 'Help'.
我可能错了,但我想我已经在里面帮助访问这个。我在一个扩展
Base
的类中,为什么不能从其他commands
访问Base
数组?
最佳答案
在大多数具有protected
概念的编程语言中,规则是Help
只能访问在Help
的实例上的受保护成员,因为这是与实现Help
类相关的所有内容。如果Base
的任何子类可以访问任何Base
的实例的受保护成员,那么任何代码都可以通过定义Base
的子类来访问任何实例的保护成员。
关于typescript - 使用私有(private) typescript 时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51715297/