简体   繁体   中英

expressjs server.js this is undefined, how can I refer to server

In an ExpressJS setup, I have server.js where I do the following:

import { call_method } from '../hereIam.mjs';

const process_db = async () => {
  console.log(this); // undefined
  call_method(this);
};

console.log(this) // undefined
process_db();

And then, from hereIam.mjs I want to call a parent method, but this is undefined

export const call_method = parent_this => console.log(parent_this); // undefined 

I tried to include classes in server.js, in an attempt to force having a this

class AppServer {
 constructor() {
   console.log(this)
 }

 const process_db = async () => call_method(this);
}

But it seems that the arrow functions inside classes doesn't compile in (experimental) NodeJS (this should be another question)

EDITED

How I can do this is by avoiding the arrow notation to be able to use classes inside Express, and then instantiate a class that provides a this .

class AppServer {
 async process_db() {call_method(this)};
}

let server = new AppServer();
server.process_db();

The question would be, the only way of getting a this reference is by using objects/classes?

You could use the the bind method and pass through any object to be used as the this context.

However, arrow functions receive the context from that which they are called from, function() {} function syntax use the context that was bound to them either implicitly by the context they were defined in or explicitly using this bind method.

So, an alternative to using classes would be to bind a simple object to the method, something like:

const call_method = require('../hereIam.mjs');

const process_db = async function() {
  console.log(this); 
  call_method(this);
};

console.log(this);

const context = {
    name: 'bound context',
    parent_method: async function() {
        console.log('Good evening');
    }
}

process_db.bind(context)();

Presuming hereIam.mjs contains:

module.exports = parent_this => console.log(parent_this);

then the script will output:

{}
{ name: 'bound context',
  parent_method: [AsyncFunction: parent_method] }
{ name: 'bound context',
  parent_method: [AsyncFunction: parent_method] }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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