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

时间:2017-01-18 12:52:21

标签: javascript typescript

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

但是我得到了variables are not defined,虽然我在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

1 个答案:

答案 0 :(得分:1)

将它们声明为if(i == j) { obj[interfaces[i].flowid] = reorderedInterfaces[j].flowid break; } 类的属性。

var interfaces = [{
  id: '123123-12-31-23',
  mac: '234',
  flowid: '1',
  status: 'deployed'
}, {
  id: '456456-12-31-23',
  mac: '45645',
  flowid: '2',
  status: 'deployed'
}, {
  id: '123123-12-31-234',
  mac: '45',
  flowid: '3',
  status: 'deployed'
}, {
  id: '456456-12-31-234',
  mac: '89',
  flowid: '4',
  status: 'deployed'
}];

var reorderedInterfaces = [

  {
    id: '456456-12-31-23',
    mac: '45645',
    flowid: '2',
    status: 'deployed'
  }, {
    id: '456456-12-31-234',
    mac: '89',
    flowid: '4',
    status: 'deployed'
  }, {
    id: '123123-12-31-234',
    mac: '45',
    flowid: '3',
    status: 'deployed'
  }, {
    id: '123123-12-31-23',
    mac: '234',
    flowid: '1',
    status: 'deployed'
  },
];


var obj = {}
for (i = 0; i < interfaces.length; i++) {
  for (j = 0; j < reorderedInterfaces.length; j++) {
    if(i == j)
    {
    obj[interfaces[i].flowid] = reorderedInterfaces[j].flowid
    break;
    }
  }

}
console.log(obj)

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

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); } } }