我有一个应该只存在一次的类,但其他类需要这个实例。我应该明确地将它传递给每个构造函数(方法 1)还是我可以只实例化一次并导出该变量(方法 2)?
// foo.ts (the shared class)
class Foo {
// ...
}
方法一:
// bar.ts (one of the classes using Foo)
class Bar {
constructor(foo: Foo) {
// ...
}
}
方法二:
// a file containing the instantiation (how to name it?)
import {Foo} from './foo';
export const foo = new Foo();
// bar.ts
import {foo} from './theFileContainingTheInstantiation';
class Bar {
// use foo
}
我知道不建议使用全局变量,但我认为方法 2 更好,因为我不必为每个类构造函数添加参数,并且可以保证唯一的实例化(我不必确保一个唯一的实例被传递给每个类)。
最佳答案
使用只读属性
export class Foo {
readonly myReadOnlyProperty = 1;
}
然后导出。阅读它只是做
import {Foo} from './foo';
var cfoo = new Foo();
console.log(cfoo.myReadOnlyProperty) // 1
您还可以导入类。先导出foo
,添加一些测试方法
export class Foo {
readonly myReadOnlyProperty = "Say";
hello() {
return "Hello,";
}
}
然后在你的文件中需要foo
。你需要扩展类
import {Foo} from './foo'; // we get foo from other file
class Bar extends Foo { // we extend foo with our new class to get it's methods
world(){
let val = this.hello(); // here you can access foo's methods
console.log(this.myReadOnlyProperty + " " + val + " world"); // Say Hello, world
}
}
let funct = new Bar();
funct.world(); // run it
关于javascript - 我可以声明一个应用程序范围的常量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56722446/