javascript - 我可以声明一个应用程序范围的常量吗?

标签 javascript typescript

我有一个应该只存在一次的类,但其他类需要这个实例。我应该明确地将它传递给每个构造函数(方法 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/

相关文章:

postgresql - 如何使用 pg-promise typescript 中的 IConfig?

在在线正则表达式测试人员中工作时,正则表达式无法在 Angular Validators.pattern() 中工作

javascript - 如何将 Promise 方法转换为 Angular 10 中的 rxjs Observables

inheritance - TypeScript 模块引用

javascript - 将 URL 更改为其他内容?

reactjs - 使用 enzyme 测试 Typescript React Component 上下文

javascript - DynamoDB batchWriteItem 在 node.js 中崩溃

javascript - 替换链接的 href 中的 src img

javascript - angular.js ng-重复除法

javascript - 与 InAppBrowser 在 Phonegap 中等效的 window.close