为什么我不能这样做?是由于 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/