我可以声明应用程序范围内的常量吗?

时间:2019-06-23 09:03:08

标签: javascript typescript

我有一个只应存在一次的类,但其他类则需要此实例。我应该将其显式传递给每个构造函数(方法1),还是可以实例化一次并导出该变量(方法2)?

// foo.ts (the shared class)
class Foo {
  // ...
}

方法1:

// bar.ts (one of the classes using Foo)
class Bar {
  constructor(foo: Foo) {
    // ...
  }
}

方法2:

// 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更好,因为我不必在每个类构造函数中添加参数,并且可以保证唯一的实例化(我不必确保将唯一的实例传递给每个类)。

1 个答案:

答案 0 :(得分:1)

使用只读属性

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
相关问题