![](/img/trans.png)
[英]JavaScript: How to create a new instance of a class without using the new keyword?
[英]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.