我有 class A
,其中一些字段通过 constructor
和 class B
extends class A
,任务是为 class A
创建 iterator
这让我有可能将它传递给 super
方法(使用扩展运算符或任何其他方式) .
Object.entries()
对我没有帮助。我该怎么做?
我认为这段代码是不言自明的。
class A {
constructor(public a: string) { }
}
class B extends A {
constructor(public b: string, a: A) {
super(...Object.entries(a));
}
}
/** can be new B('b', new A('a'));
* But not the new B('b', 'a') actually
*/
const b = new B('b', { a: 'a' });
console.log(b); // expect to get {b: 'b', a: 'a'}
// actually get {b: 'b', a: ['a', 'a']}
最佳答案
给你两个答案:
回答您的问题,以及
提出不同的方法
回答你的问题
我不认为你可以做你所描述的。尽管您可以让 Symbol.iterator
函数以与 A
的构造函数的参数列表相同的顺序返回您创建的数组的迭代器:
class A {
constructor(public a: string) {
}
[Symbol.iterator]() {
return [this.a][Symbol.iterator]();
}
}
...问题是 super
调用无法编译,TypeScript 提示:
super(...a); // Expected 1 arguments, but got 0 or more.
当然,除了使用 @ts-ignore
禁用该错误之外,我没有看到解决该问题的方法。 :
// @ts-ignore
super(...a); // Expected 1 arguments, but got 0 or more.
...这似乎不是个好主意。 (Live example 在 Playground 上。)
提出不同的方法
即使你可以这样做,我也不推荐它,它很脆弱:如果你改变了 A
的构造函数中的参数顺序,你需要改变你的迭代器匹配。让它们保持同步将是一个维护陷阱。
相反,我会让构造函数能够接受 A
的实例并复制它的所有属性:
class A {
public a: string = "";
constructor(a: string);
constructor(obj: A);
constructor(x: string|A) {
if (x instanceof A) {
Object.assign(this, x);
} else {
this.a = x;
}
}
}
super
调用将是:
super(a);
关于javascript - 将对象作为函数参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58709555/