[英]Error creating class with properties in the constructor
I have created this class:我创建了这个类:
export class ModelTransformer {
constructor(private readonly hostelTransformer: HostelTransformer) {}
static transform(hostel: Hostel): Hotel {
return hostelTransformer.transform(hostel);
}
}
But when I compile it I have this compilation error:但是当我编译它时,我有这个编译错误:
error TS2304: Cannot find name 'hostelTransformer'.错误 TS2304:找不到名称“hostelTransformer”。
I also tried我也试过
static transform(hostel: Hostel): Hotel {
return this.hostelTransformer.transform(hostel);
}
but then I have the error:但后来我有错误:
error TS2339: Property 'hostelTransformer' does not exist on type 'typeof ModelTransformer'.
You can't access the instance properties inside static methods.您无法访问静态方法中的实例属性。
When you use private readonly hostelTransformer: HostelTransformer
in the constructor, it goes on the instance of the ModelTransformer
class.当您在构造函数中使用private readonly hostelTransformer: HostelTransformer
时,它会在ModelTransformer
类的实例上ModelTransformer
。 Like this像这样
constructor(hostelTransformer) {
this.hostelTransformer = hostelTransformer;
}
You can't use return this.hostelTransformer.transform(hostel)
because transform
is a static method.你不能使用return this.hostelTransformer.transform(hostel)
因为transform
是一个静态方法。 When you call ModelTransformer.transform()
, this
will be ModelTransformer
and not the instance of the class.当您调用ModelTransformer.transform()
, this
将是ModelTransformer
而不是类的实例。
If you want to use that property, you need to make the method non-static如果要使用该属性,则需要将该方法设为非静态
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.