javascript - 从Typescript中的实例访问静态方法

标签 javascript static typescript

为什么我不能这样做?是由于 Javascript/Typescript 的技术限制,还是 Typescript 开发人员的设计决定?同样的代码在 Java 或 C# 中也能正常工作。

class Test {
  static str: string = "test";
  public static getTest(): string {
    return this.str;
  }
}

//works as expected
console.log(Test.getTest());
//won't compile
var test: Test = new Test();
console.log(test.getTest());

最佳答案

but I'd still like to know why.

减少魔法。静态属性存在于 Class 而不是实例中。它清楚地表明在运行时从代码中调用了什么,而不是魔术绑定(bind)到类或成员函数。

Is it due to technical limitations of Javascript/Typescript, or is this a design decision by the developers of Typescript

不是技术限制。一个设计决定。比其他任何东西都更符合 ES6:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static但在那边,它是为减少魔法而做出的决定

关于javascript - 从Typescript中的实例访问静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33864167/

相关文章:

java - 即使我将 1 个数组的值存储到另一个数组中并将它们作为一个整体打印,但数组仍然打印最后一个值

c++ - 为什么从函数返回时需要将数组声明为静态数组。 (C++)

typescript - 带有 `src` 和 `tests` 的项目的 tsconfig.json

angular - 如何直接转到选项卡

javascript - preg_match 用于验证自定义模式

javascript - 限制浏览器中显示的 PDF 页数

javascript - 单击按钮时出现 Selenium 错误 : . MoveTargetOutOfBoundsException

javascript - 调用另一个类的函数

PHP:静态和非静态函数和对象

angular - 找不到名称 'grecaptcha'