Javascript 访问内部函数类型脚本中的外部变量

Javascript 访问内部函数类型脚本中的外部变量,javascript,typescript,Javascript,Typescript,我有一个函数外的变量,我需要改变它的值。我通常使用“this”来访问变量,但在代码的这一点上,“this”是不可访问的 export class GamesDetailPage { details : any = {}; type : String; level : Number; cards : any = {}; // THE VARIABLE I WANT TO SET THE VALUE constructor(public navCtrl: NavContr

我有一个函数外的变量,我需要改变它的值。我通常使用“this”来访问变量,但在代码的这一点上,“this”是不可访问的

export class GamesDetailPage {

  details : any = {};
  type : String;
  level : Number; 
  cards : any = {}; // THE VARIABLE I WANT TO SET THE VALUE


  constructor(public navCtrl: NavController, public http: HttpClient , private device: Device, private serviceProvider: ServicesProvider,     
                                            public navParams: NavParams
) {
    this.type = navParams.get('gameType');
    this.level = navParams.get('gameLevel');
  }

  ionViewDidLoad() {


    this.getCards();  // WHERE I CALL THE METHOD  
  }


  getCards(){
    var deviceUUID = this.device.uuid;
    var platform =  this.device.platform;
    var cardsReq = {"gameType": this.type ,"gameLevel": this.level};
    var dialog = this.dialogs;

   this.serviceProvider.getCards(deviceUUID, platform, cardsReq)

    .then(function (res){
      this.cards = res;// HERE I WANT TO SET THE VARIABLE BUT "THIS" IS UNDEFINED
    })
    .catch(function(err){
      console.log("Error");
    })
  }
}
在这里,您需要像前面的
(function(){
方法
中一样使用此
不引用该类,但在es6中它将

箭头函数表达式的语法比函数表达式短,并且没有自己的语法


因为函数的外部
this
this
遮挡。 最直接的方法也是推荐的方法是在typescript中使用arrow函数

将lambda函数更改为:

(res) => {}
另一个旧的解决方案是将此保存到临时变量:

that = this

然后在lambda函数中访问该函数。

在JavaScript
中,此
与当前函数相关。TypeScript在传输代码时仅隐藏此事实

因此,你可以做两件事

首先,您可以使用ES6箭头函数(TypeScript将为您执行
this
scoping)

或者你可以自己处理

getCards(){
    var _this = this;

    // More code

    .then(function (res){
        _this.cards = res;
    })

如果您检查两种情况下的传输输出,它们应该几乎相同

此解决方案的可能副本对我有效。Old is gold感谢@Eliott
.then((res) => {
    this.cards = res;
})
getCards(){
    var _this = this;

    // More code

    .then(function (res){
        _this.cards = res;
    })