如何在Deno中定义全局变量? [英] How to define global variable in Deno?

查看:80
本文介绍了如何在Deno中定义全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Deno和TypeScript的新手,但是拥有使用NodeJ和Javascript的丰富经验,我偶然发现了一个问题,只需将 global 添加到NodeJs中,就可以很容易地在NodeJs中进行分类.但是,出于某种原因,在Deno中这种混合显示相当困难.

I am new to Deno and TypeScript but have plenty of experience using NodeJs and Javascript, I have stumbled on an issue of sorts, that I could have easily sorted out in NodeJs by simply adding global into the mix, however, that shows to be rather difficult in Deno for some reason.

我想声明 First 变量,该变量应该在全球范围内可用,而无需导入它.(可以使用类似 Deno 的变量)

I want to declare the First variable that should be available globally everywhere without need to import it. (sort of like Deno variable is available)

这是我尝试运行的代码示例:

Here is an example of the code I'm trying to get running:

/// index.ts
import { FirstClass } from './FirstClass.ts';

global.First = new FirstClass();

await First.commit();

/// FirstClass.ts
import { SecondClass } from './SecondClass.ts';
export class FirstClass {
  constructor() {}
  async commit() {
    const second = new SecondClass();

    await second.comment();
  }
}

/// SecondClass.ts
export class SecondClass {
  constructor() {}
  comment() {
    console.log(First); // Should log the FirstClass
  }
}

我将像这样运行这段代码: deno run index.ts

I would run this code like this: deno run index.ts

推荐答案

Deno中的全局对象是: window / globalThis

The global object in Deno is: window / globalThis

window.First = new FirstClass();

有关TypeScript编译器错误,请参见:如何在TypeScript中的"window"上显式设置新属性?

For TypeScript compiler errors see: How do you explicitly set a new property on `window` in TypeScript?

declare global {
    var First: FirstClass
    interface Window { First: any; }
}

window.First = new FirstClass();
await First.commit();

这篇关于如何在Deno中定义全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆