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

前端之家收集整理的这篇文章主要介绍了javascript – 从Typescript中的实例访问静态方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

  1. class Test {
  2. static str: string = "test";
  3. public static getTest(): string {
  4. return this.str;
  5. }
  6. }
  7. //works as expected
  8. console.log(Test.getTest());
  9. //won't compile
  10. var test: Test = new Test();
  11. console.log(test.getTest());
最佳答案

but I’d still like to know why.

少魔法.静态属性存在于Class not实例上.它清楚地知道从代码调用什么而不是在运行时魔术绑定到类或成员函数.

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相关文章