javascript - 在 TypeScript 中以不同方法访问变量

标签 javascript typescript

我有下面的简单代码,其中在 Main 方法中定义了 2 个变量,我需要从另一个方法访问它们。

但是我得到了变量未定义,尽管我在declerations/main.d.ts文件中将它们定义为:

declare let voiceReady:any;
declare let x:any;

main.ts 文件是;

/// <reference path="../declerations/main.d.ts" />
namespace CORE{
    export class Program {
      public static Main(): void {
            var voiceReady = new CORE.Listen(CORE.commands).commands;
            console.log(voiceReady);
            var x = 560;
            Program.execute('anything');
     }


        public static execute(spokenText:string):void{
            console.log('123');
            console.log(x);
            console.log(voiceReady);
       }
    }
}

更新 如果我从 .d.ts 文件中删除减速,并将它们添加到 class 本身,则会出现编译错误,如下所示:

enter image description here

最佳答案

将它们声明为 Program 类的属性。

namespace CORE{
export class Program {

    //Declare the properties here and access them in the methods
    static voiceReady: any;       

    public static Main(): void {
      this.voiceReady = new CORE.Listen(CORE.commands).commands;
      console.log(this.voiceReady);
      Program.execute('anything');
    }

    public static execute(spokenText:string):void{
        console.log(this.voiceReady);
     }
  }
}

如果您想从另一个类引用,请将其导入到模块外部,例如

import { Program } from "./Program"; 

并在您的类中使用它,例如 Program.Main();

关于javascript - 在 TypeScript 中以不同方法访问变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41719936/

相关文章:

javascript - 使用each()打印数组时jquery ajax()问题

javascript - 无法让defaultsTo与waterline/sailsjs一起使用

javascript - 等待函数输出不超过一定时间的最佳方法是什么?

javascript - 控制 popup.html 弹出的时间

javascript - Angular 2 - 如何在指令上设置动画?

angular - IE11 上的 Webpack + Angular(4) + ES6 无法正常工作

angular - MatTable 上的多个过滤器

javascript - 带有 HTML 标记的桌面通知(代码示例)?

angular - canActivate 上结束 return 语句的问题

typescript - 如何在 Angular2 中触发变化检测?