繁体   English   中英

如何在没有“新”关键字的情况下创建类的实例

[英]How to Create an Instance of the Class without “new” Keyword

该项目是带有TypeScript的NodeJS项目。

我想创建一个App类的实例。 但是,如果我使用new关键字,则必须传递构造函数参数。

问题在于构造函数参数应与依赖项注入一起传递。 因此,我无法使用new关键字创建实例。

// Express
import { application as app } from 'express';

// Controllers
import { UserController } from './controllers/user.controller'

export class App {
  constructor(userController: UserController) {
    console.log("App is running");
    console.log("UserController url path is : ", userController.getUrlPath);

    this.run();
  }

  run(): void {
    app.listen(3000, function () {
      console.log('App is running on port 3000!');
    });
  }

  check(): void {
    console.log("working well");
  }
}

const appInstance: App = <App>Object.create(App.prototype); // it is not creating

console.log( appInstance.check() ); // ==> 'undefined'

这似乎与使用类的概念背道而驰
如果您需要避免出于测试目的而传递具体的UserController ,则可以使用某种形式的模拟。
另一种选择是使用any类型的变量:

const app = new App({} as any);

根据您的tsconfig.json配置,它应该可以工作(显然,您将无法访问UserController对象的任何功能/字段,但是App的构造应该可以正常工作。
最后一个选项(至少可以想到)是为UserController使用setter函数:

export class App {
 private _userController: UserController;
 get userController(): UserController {
  return this._userController;
 }
 set userController(ctrl: UserController) {
  this._userController = ctrl;
 }
}

这样,在设置完整的DI基础结构之后,您可以使用App.userController = SOME_USER_CONTROLLER_FROM_DI

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM