为什么我不能这样做?是由于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 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但在那里它的决定是为了减少魔法