调用类的公共方法(错误:不是函数)

时间:2019-09-11 14:52:37

标签: typescript ionic-framework ionic3

我在文件sessionKotiz中创建了一个类session.ts,如下所示:

export class SessionKotiz{
    designation : string;
    total_in : number;
    total_out: number;

    constructor(){
        total_in = 0;
        total_out = 0;
    }

    reset(){
        total_in = 0;
        total_out = 0;
    }
}

现在,在另一个文件(实际上是页面)中,我有一个类型为SessionKotiz的成员

  export class InfoSessionPage {
  title     : any;
  items     : SessionKotiz = new SessionKotiz();


  constructor(public navCtrl: NavController, public navParams: NavParams,
              public events:Events,          public store: StoreAPI,
              private alertCtrl: AlertController) {

    this.items = new SessionKotiz();
  }

  resetSession(){
  let alert = this.alertCtrl.create({
    title: 'Confirm reset',
    message: 'Do you want reset current session?',
    buttons: [
      {
        text: 'Cancel',
        role: 'cancel',
        handler: () => {
          console.log('Cancel clicked');
        }
      },
      {
        text: 'reset',
        handler: () => {
          console.log('reset clicked');
          // Reset report
          this.items.reset();
        }
      }
    ]
  });
  alert.present();
}

在代码的某个时刻,我想调用reset()类的方法SessionKotiz,但是错误提示

_this.items.reset is not a function

该如何解决?如何在打字稿中调用方法?

1 个答案:

答案 0 :(得分:0)

尝试一下。

export class SessionKotiz{
    designation : string;
    total_in : number;
    total_out: number;

    constructor(){
        this.total_in = 0;
        this.total_out = 0;
    }

    reset(){
        this.total_in = 0;
        this.total_out = 0;
    }
}

resetSession(){
  let self = this;//magic
  let alert = this.alertCtrl.create({
    title: 'Confirm reset',
    message: 'Do you want reset current session?',
    buttons: [
      {
        text: 'Cancel',
        role: 'cancel',
        handler: () => {
          console.log('Cancel clicked');
        }
      },
      {
        text: 'reset',
        handler: () => {
          console.log('reset clicked');
          // Reset report
          self.items.reset();//magic
        }
      }
    ]
  });

  alert.present();
}