calling function inside javascript class : this.function is not a function

hretic

i've already seen this

How to access the correct `this` inside a callback

it doesn't mention classes , at least this syntax im using

im new to nodejs and js class so bear with me , im writing a app with mvc like architecture

i got two methods in my controller , wallet and generateWallet

user will call wallet method via http request, it will check the database for wallet and if not exists it will call another function generateWallet which is supposed to be a private function to generate a new wallet and thats when i get the error

here i my code

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();

here is the error

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)

specifically this like

let newWallet = await this.generateWallet(); 

i assume something is changing this keyword but i cant figure out what , there are routers and other codes involved in the stack but i dont think they have any effect since we are inside the function when we get this error ?

here is how i've set up my filder/files

so i have router folder with api and web folder inside , containing route files for each section for example in routes/api/dashboard.js i have

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,
    },
  ],
};

and i have routes/inedx.js which grabs all the route files and adds them to express

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();

i have 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 ;

and finally my index.js

const Server = require('./server/index');
const app = new Server(8080);
app.start();
Arootin Aghazaryan

Problem you are having is related to how you assign the DashboardController.wallet to the handler which makes this to be unbound:

{
  method: "get",
  path: "/wallet",
  handler: DashboardController.wallet,
}

Since you don't have class variables, you can make your methods static and not use this at all:

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;

alternatively, you can use .bind() to set the this explicitly:

{
  method: "get",
  path: "/wallet",
  handler: DashboardController.wallet.bind(DashboardController),
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Calling a recursive function inside a class

From Dev

Initiating and calling a function inside class

From Dev

Calling an async function inside a class

From Javascript

Calling a Function defined inside another function in Javascript

From Dev

Javascript calling function from inside same function

From Dev

Calling a function inside another function in JavaScript

From Dev

Javascript: Calling a function inside another function

From Dev

Calling JavaScript sibling function inside parent function

From Dev

Calling the main function inside a callback function in javascript

From Dev

Calling javaScript function by a JavaScript class

From Dev

Get calling Event inside of Class-Function without Parameter in JavaScript

From Dev

PHP Calling A Class function inside B Class

From Dev

Calling class instance as a function in JavaScript

From Dev

JS - Calling class methods inside of callback function

From Dev

Creating and calling a custom function inside an angular class

From Java

Calling a class function inside of __init__

From Dev

Calling a function inside same class not working, typescript

From Dev

Calling a function pointer inside the same class

From Dev

Calling a Function Inside Map Function

From Dev

Calling a function inside a function in C

From Dev

C++ calling a class function inside another function

From Dev

Calling Graph API inside a javascript Azure Function

From Dev

Calling a javascript function inside a vue component file

From Dev

Javascript function calling inside an array of objects?

From Dev

Calling a JavaScript function inside PHP Array

From Dev

JavaScript function inside echo in PHP script is not calling

From Dev

Calling function inside function in another function

From Dev

Calling a function inside JSX

From Dev

calling a async function inside then

Related Related

  1. 1

    Calling a recursive function inside a class

  2. 2

    Initiating and calling a function inside class

  3. 3

    Calling an async function inside a class

  4. 4

    Calling a Function defined inside another function in Javascript

  5. 5

    Javascript calling function from inside same function

  6. 6

    Calling a function inside another function in JavaScript

  7. 7

    Javascript: Calling a function inside another function

  8. 8

    Calling JavaScript sibling function inside parent function

  9. 9

    Calling the main function inside a callback function in javascript

  10. 10

    Calling javaScript function by a JavaScript class

  11. 11

    Get calling Event inside of Class-Function without Parameter in JavaScript

  12. 12

    PHP Calling A Class function inside B Class

  13. 13

    Calling class instance as a function in JavaScript

  14. 14

    JS - Calling class methods inside of callback function

  15. 15

    Creating and calling a custom function inside an angular class

  16. 16

    Calling a class function inside of __init__

  17. 17

    Calling a function inside same class not working, typescript

  18. 18

    Calling a function pointer inside the same class

  19. 19

    Calling a Function Inside Map Function

  20. 20

    Calling a function inside a function in C

  21. 21

    C++ calling a class function inside another function

  22. 22

    Calling Graph API inside a javascript Azure Function

  23. 23

    Calling a javascript function inside a vue component file

  24. 24

    Javascript function calling inside an array of objects?

  25. 25

    Calling a JavaScript function inside PHP Array

  26. 26

    JavaScript function inside echo in PHP script is not calling

  27. 27

    Calling function inside function in another function

  28. 28

    Calling a function inside JSX

  29. 29

    calling a async function inside then

HotTag

Archive