从打字稿中的非静态函数访问静态成员 [英] accessing static member from non-static function in typescript

查看:37
本文介绍了从打字稿中的非静态函数访问静态成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从类中的非静态函数访问静态成员,但收到一条错误消息

I am trying to access a static member from a non-static function in the class, and I get an error saying

不能通过实例变量访问静态成员

Static member cannot be accessed off an instance variable

这是我的代码的样子 -

this is how my code looks -

class myClass {
  public static testStatic: number = 0;
  public increment(): void {
    this.testStatic++;
  }
}

根据我对静态成员/方法的理解,我们不应该访问静态函数中的非静态成员,但反之亦然.静态成员已经创建并且有效,为什么我不能从我的非静态方法访问?

From what I understand of static members/methods, we shouldn't access non-static members in static functions, but vice-versa should be possible. the static member is already created and is valid, so why can't I access from my non-static method?

推荐答案

从类内部访问静态成员的方式与从类外部相同:

Access static members from inside the class the same way you would from outside the class:

class myClass {
  public static testStatic: number = 0;
  public increment(): void {
    myClass.testStatic++;
  }
}

这篇关于从打字稿中的非静态函数访问静态成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆