简体   繁体   English

在构造函数中创建具有属性的类时出错

[英]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.

相关问题 创建导出的声明类的实例以“不是构造函数”错误结束 - Creating instance of exported declared class ended up with 'is not a constructor' error JavaScript:如何在 Class 语法的构造函数中定义错误以拒绝创建实例? - JavaScript: How to define an error in the constructor of Class syntax to deny creating an instance? 在构造函数中的Promise中设置类属性 - Setting class properties in a promise in a constructor 类属性:在父构造函数中访问子类属性 - Class properties: Access child class properties in parent constructor 打字稿错误:当类包含初始化的属性时,“超级”调用必须是构造函数中的第一条语句 - Typescript error : A 'super' call must be the first statement in the constructor when a class contains initialized properties Typescript是否在类构造函数中设置接口属性? - Does Typescript set interface properties in the Class Constructor? javascript mixins中的构造方法和类属性 - Constructor and class properties within javascript mixins JavaScript:从父 Class 继承构造函数属性 - JavaScript : Inherit constructor properties from Parent Class javascript 中的超级 class 的构造函数和继承属性 - Constructor and inheriting properties from super class in javascript 创建空构造函数并在 class 中初始化数组时出现问题 - Problems creating an empty constructor, and initializing an array in a class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM