[英]How to Create an Instance of the Class without “new” Keyword
This project is NodeJS project with TypeScript. 该项目是带有TypeScript的NodeJS项目。
I want to create an instance of App class. 我想创建一个App类的实例。 But, if I use
new
keyword, I have to pass constructor parameter. 但是,如果我使用
new
关键字,则必须传递构造函数参数。
The problem is that constructor parameter should be passed with dependency injection. 问题在于构造函数参数应与依赖项注入一起传递。 So, I can't use
new
keyword to create an instance. 因此,我无法使用
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'
This seems to go against the very concept of using classes 这似乎与使用类的概念背道而驰
If you need to avoid passing a concrete UserController
for testing purposes, you can use some form of mock. 如果您需要避免出于测试目的而传递具体的
UserController
,则可以使用某种形式的模拟。
Another option is to use a variable of type any
: 另一种选择是使用
any
类型的变量:
const app = new App({} as any);
Depending on your tsconfig.json
configuration, it should work (obviously you won't be able to access any of the functions/fields of the UserController
object, but the construction of App
should work just fine. 根据您的
tsconfig.json
配置,它应该可以工作(显然,您将无法访问UserController
对象的任何功能/字段,但是App
的构造应该可以正常工作。
The last option (I could think of at least) is using a setter function for the UserController
: 最后一个选项(至少可以想到)是为
UserController
使用setter函数:
export class App {
private _userController: UserController;
get userController(): UserController {
return this._userController;
}
set userController(ctrl: UserController) {
this._userController = ctrl;
}
}
And this way, after setting up a full DI infrastructure, you can use App.userController = SOME_USER_CONTROLLER_FROM_DI
这样,在设置完整的DI基础结构之后,您可以使用
App.userController = SOME_USER_CONTROLLER_FROM_DI
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.