我有下面的简单代码,其中在 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
本身,则会出现编译错误,如下所示:
最佳答案
将它们声明为 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/