gpt4 book ai didi

static - typescript 类 : statics and inheritance

转载 作者:搜寻专家 更新时间:2023-10-30 21:01:28 26 4
gpt4 key购买 nike

问题:

  1. 我观察到的行为是 TypeScript 的预期行为吗?
  2. 我观察到的行为是 ECMAScript 6 的预期行为吗?
  3. 是否有一种简单的方法可以返回继承层次结构以处理每个级别的“myStatic”数组?我怎么知道什么时候停止?

描述:使用 TypeScript 时,派生类和静态属性似乎有一些有趣的行为。

TypeScript Example

class MyBase {
static myStatic = [];
}

class MyDerived extends MyBase {}

MyBase.myStatic = ['one', 'two', 'three']

class MyDerived2 extends MyBase {}

document.body.innerHTML += "<b>MyDerived.myStatic:</b>&nbsp;" + JSON.stringify(MyDerived.myStatic) + "<br/>";
document.body.innerHTML += "<b>MyDerived2.myStatic:</b>&nbsp;" + 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>&nbsp;" + JSON.stringify(MyDerived.myStatic()) + "<br/>";
document.body.innerHTML += "<b>MyDerived2.myStatic:</b>&nbsp;" + JSON.stringify(MyDerived2.myStatic()) + "<br/>";

TypeScript 结果:

MyDerived.myStatic: []
MyDerived2.myStatic: ["one","two","three"]

ECMA 脚本 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 脚本 6 结果

MyDerived.myStatic: ["one","two","three"]
MyDerived2.myStatic: ["one","two","three"]

最佳答案

Is the behavior I'm observing the expected behavior for TypeScript? Is the behavior I'm observing the expected behavior for ECMA Script 6?

是的,是的。类允许运行时修改并按定义顺序处理。 inherit 仅在定义点生效,因此取决于基在该点 的属性。

关于static - typescript 类 : statics and inheritance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27765302/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com