我已經看過了
如何在回呼中訪問正確的`this`
它沒有提到類,至少我正在使用這種語法
我是 nodejs 和 js 類的新手,所以請多多包涵,我正在用類似 mvc 的架構撰寫一個應用程式
我的控制器中有兩種方法,wallet并且generateWallet
用戶將wallet通過http請求呼叫方法,它將檢查資料庫中的錢包,如果不存在,它將呼叫另一個函式generateWallet,該函式應該是一個私有函式來生成一個新的錢包,這就是我收到錯誤的時候
這是我的代碼
class DashboardController {
async wallet(req, res) {
let wallet = await UserWalletRepository.find({
user_id: req.authUser.id,
});
if (wallet) return res.send(wallet);
let newWallet = await this.generateWallet();
res.send(newWallet);
}
async generateWallet() {
let generatedWallet = await WalletService.generateWallet();
let newWallet = await UserWalletRepository.create({
user_id: req.authUser.id,
...generatedWallet,
});
return newWallet;
}
}
module.exports = new DashboardController();
這是錯誤
TypeError: this.generateWallet is not a function
at wallet (C:\node\first\app\controller\api\dashboard-controller.js:16:32)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
特別是這樣
let newWallet = await this.generateWallet();
我假設某些東西正在改變this關鍵字,但我不知道是什么,堆疊中涉及路由器和其他代碼,但我認為它們沒有任何影響,因為當我們收到此錯誤時我們在函式內部?
這是我設定檔案/檔案的方式
所以我有一個router檔案夾api和web里面的檔案夾,包含每個部分的路由檔案,例如routes/api/dashboard.js我有
const DashboardController = require("../../app/controller/api/dashboard-controller");
const { AuthMiddleware } = require("../../app/middleware/auth");
module.exports = {
group: {
prefix: "/dashboard",
middleware: [AuthMiddleware],
},
routes: [
{
method: "get",
path: "/",
handler: DashboardController.index,
},
{
method: "get",
path: "/wallet",
handler: DashboardController.wallet,
},
],
};
我有routes/inedx.js它抓取所有路由檔案并將它們添加到表達
const express = require("express");
require("express-async-errors");
const webRoutes = require("./web/index");
const apiRoutes = require("./api/index");
class Router {
constructor() {
this.router = express.Router();
}
create(app) {
this._attachMiddleware();
this._attachWebRoutes();
this._attachApiRoutes();
app.use(this.router);
}
_attachMiddleware() {
this.router.use(express.json());
}
_attachWebRoutes() {
this._attachRoutes(webRoutes);
}
_attachApiRoutes() {
this._attachRoutes(apiRoutes, "/api");
}
_attachRoutes(routeGroups, globalPrefix = "") {
routeGroups.forEach(({ group, routes }) => {
routes.forEach(({ method, path, middleware = [], handler }) => {
this.router[method](
globalPrefix group.prefix path,
[...(group.middleware || []), ...middleware],
handler
);
});
});
}
}
module.exports = new Router();
我有server/index.js
const express = require('express')
const Router = require('../router/index')
class Server {
constructor(port){
this.port = port ;
this.app = express();
}
start(){
this._setupRoutes();
this._listin();
}
_listin(){
this.app.listen(this.port , ()=>{
console.log('app running on port' , this.port);
})
}
_setupRoutes(){
Router.create(this.app)
}
}
module.exports = Server ;
最后是我的index.js
const Server = require('./server/index');
const app = new Server(8080);
app.start();
uj5u.com熱心網友回復:
您遇到的問題與您如何將其分配DashboardController.wallet給處理程式有關,從而使處理程式this不受約束:
{
method: "get",
path: "/wallet",
handler: DashboardController.wallet,
}
由于您沒有類變數,因此您可以將方法設為靜態并且根本不使用this:
class DashboardController {
static async wallet(req, res) {
let wallet = await UserWalletRepository.find({
user_id: req.authUser.id,
});
if (wallet) return res.send(wallet);
let newWallet = await DashboardController.generateWallet();
res.send(newWallet);
}
static async generateWallet() {
let generatedWallet = await WalletService.generateWallet();
let newWallet = await UserWalletRepository.create({
user_id: req.authUser.id,
...generatedWallet,
});
return newWallet;
}
}
module.exports = DashboardController;
或者,您可以使用顯式.bind()設定this:
{
method: "get",
path: "/wallet",
handler: DashboardController.wallet.bind(DashboardController),
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/487456.html
標籤:javascript 节点.js 表示
