【问题标题】:call a class's public method (error: is not a function)调用类的公共方法(错误:不是函数)
【发布时间】:2020-01-13 10:49:12
【问题描述】:

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

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

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

_this.items.reset is not a function

我该如何解决这个问题?如何在 typescript 中调用方法?

【问题讨论】:

  • @NicholasTower 是的,我在 infoPage 类的构造函数中做到了
  • @NicholasTower 我编辑了代码
  • 我没有看到你打电话给_this.item.reset()的任何地方。
  • 我已经删除了我的 cmets 和我的答案,因为新代码与旧代码有很大不同。它还存在变量名称不匹配的情况,因此它只能是正在发生的事情的近似值。
  • this.items = new SessionKotiz(); _this.item.reset 不是一个函数......也许你在调用 _this.item.reset 时缺少“s”

标签: typescript ionic-framework ionic3


【解决方案1】:

试试这个。

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

【讨论】:

    猜你喜欢
    • 2018-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-19
    • 2011-01-30
    相关资源
    最近更新 更多