问题:
- 我观察到的行为是否符合TypeScript的预期行为?
- 我观察到的行为是否符合ECMAScript 6的预期行为?
- 有没有一种简单的方法可以沿继承层次结构向后遍历,以处理每个级别的“myStatic”数组?我如何知道何时停止?
描述:在使用TypeScript时,派生类和静态属性之间似乎存在一些有趣的行为。
class MyBase {
static myStatic = [];
}
class MyDerived extends MyBase {}
MyBase.myStatic = ['one', 'two', 'three']
class MyDerived2 extends MyBase {}
document.body.innerHTML += "<b>MyDerived.myStatic:</b> " + JSON.stringify(MyDerived.myStatic) + "<br/>";
document.body.innerHTML += "<b>MyDerived2.myStatic:</b> " + JSON.stringify(MyDerived2.myStatic) + "<br/>";
这是结果:
MyDerived.myStatic: []
MyDerived2.myStatic: ["one","two","three"]
编辑:添加一个例子以说明TypeScript和ECMA Script 6之间不同的行为。注意:ECMA Script不支持静态属性,因此这些示例使用静态方法。
TypeScript代码:
class MyBase {
static myStatic() { return []; }
}
class MyDerived extends MyBase {}
MyBase.myStatic = () => { return ['one', 'two', 'three']; }
class MyDerived2 extends MyBase {}
document.body.innerHTML += "<b>MyDerived.myStatic:</b> " + JSON.stringify(MyDerived.myStatic()) + "<br/>";
document.body.innerHTML += "<b>MyDerived2.myStatic:</b> " + JSON.stringify(MyDerived2.myStatic()) + "<br/>";
TypeScript结果:
MyDerived.myStatic: []
MyDerived2.myStatic: ["one","two","three"]
ECMA Script 6 Code: ES6 Fiddle
class MyBase {
static myStatic() { return []; }
}
class MyDerived extends MyBase {}
MyBase.myStatic = () => { return ['one', 'two', 'three']; };
class MyDerived2 extends MyBase {}
console.log("MyDerived.myStatic: " + JSON.stringify(MyDerived.myStatic()));
console.log("MyDerived2.myStatic: " + JSON.stringify(MyDerived2.myStatic()));
ECMA Script 6 的结果
MyDerived.myStatic: ["one","two","three"]
MyDerived2.myStatic: ["one","two","three"]