我有一个 Foo 和一个 Bar 类:
class Foo {
private name: string;
private bar: Bar;
constructor(name: string, bar: Bar) {
this.name = name;
this.bar = bar;
}
}
class Bar {
private x: number;
private y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
现在使用 Typescript 构造函数速记,我可以将 Foo 写为:class Foo {
constructor(private name: string, private bar: Bar) { }
}
但是,我想做的不是传递 Bar
对象进入 Foo
构造函数。而是传入 x
的值和 y
,但仍然保持使用速记符号来节省我完整写出类(class)的时间。实际上,可以这样:
class Foo {
private name: string;
private bar: Bar;
constructor(name: string, x: number, y: number) {
this.name = name;
this.bar = new Bar(x, y);
}
}
是使用速记符号书写的吗?
最佳答案
速记符号称为 "parameter properties" ,特别是只是将构造函数参数复制到同名的类属性。它不适合你正在做的事情 bar
.您仍然可以使用 name
的简写。属性,像这样:
class Foo {
private bar: Bar;
constructor(private name: string, x: number, y: number) {
this.bar = new Bar(x, y);
}
}
这就是我建议您继续进行的方式。如果有人以人身伤害威胁我,除非我想出一些方法来为您的
bar
使用参数属性场景,我想我可以滥用 default parameters像这样:// ☠ DON'T DO THIS ☠
class AbuseFoo {
constructor(
private name: string,
x: number, y: number,
private bar: Bar = new Bar(x, y)
) { }
}
这在那个“起作用”// ☠ DON'T DO THIS ☠
let f = new AbuseFoo("name", 1, 2);
console.log(JSON.stringify(f)); // {"name":"name","bar":{"x":1,"y":2}}
生成一个包含私有(private) bar
的值x
的属性(property)是 1
和 y
是 2
.但它公开了一个可选的第四个构造函数参数,该参数覆盖 x
和 y
特性:f = new AbuseFoo("name", 1, 2, new Bar(3, 4));
console.log(JSON.stringify(f)); // {"name":"name","bar":{"x":3,"y":4}}
当然,它比仅仅声明 bar
更丑陋和复杂。在类中并以正常方式在构造函数中设置它。因此,除非您有充分的理由这样做(例如,代码混淆竞赛、人身伤害威胁等),否则我会坚持原来的答案:不可以,不能使用参数属性设置
bar
那样。使用速记方法。 Playground link to code
关于 typescript 在速记构造函数中创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64064704/