问题:
描述:使用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脚本6之间不同行为的示例。注意:ECMA脚本不支持静态属性,因此这些示例使用静态方法。
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代码: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"]
答案 0 :(得分:1)
我是否正在观察TypeScript的预期行为? 我是否正在观察ECMA Script 6的预期行为?
是的,是的。类允许运行时修改并按定义顺序处理。 inherit
仅在定义点开始,因此取决于该点的基本属性。
答案 1 :(得分:0)
See related TypeScript bug report
以下是TypeScript和ES6代码示例,它们具有一致的行为并遍历继承层次结构:
TypeScript代码:
class MyBase {
static myStatic() { return []; }
}
class MyDerived extends MyBase {
static myStatic() { return ['mickey', 'goofy', super.myStatic()]; }
}
MyBase.myStatic = () => { return ['one', 'two', 'three']; };
class MyDerived2 extends MyBase {
static myStatic() { return ['mickey', 'goofy', super.myStatic()]; }
}
document.body.innerHTML += ("MyDerived.myStatic: " + JSON.stringify(MyDerived.myStatic()) + "<br/>");
document.body.innerHTML += ("MyDerived2.myStatic: " + JSON.stringify(MyDerived2.myStatic()) + "<br/>");
TypeScript结果:
MyDerived.myStatic: ["mickey","goofy",["one","two","three"]]
MyDerived2.myStatic: ["mickey","goofy",["one","two","three"]]
ES6代码:ES6 Fiddle
class MyBase {
static myStatic() { return []; }
}
class MyDerived extends MyBase {
static myStatic() { return ['mickey', 'goofy', super.myStatic()]; }
}
MyBase.myStatic = () => { return ['one', 'two', 'three']; };
class MyDerived2 extends MyBase {
static myStatic() { return ['mickey', 'goofy', super.myStatic()]; }
}
console.log("MyDerived.myStatic: " + JSON.stringify(MyDerived.myStatic()));
console.log("MyDerived2.myStatic: " + JSON.stringify(MyDerived2.myStatic()));
ES6结果
MyDerived.myStatic: ["mickey","goofy",["one","two","three"]]
MyDerived2.myStatic: ["mickey","goofy",["one","two","three"]]