Passing an ES6 class class as an argument to a function called inside a function

How to fix the code below to be able to call the class method using call .

Class definition:

 class User { constructor(..) {...} async method(start, end) {} } 

Trying to pass a class method as an argument to a function:

 const User = require('./user'); async function getData(req, res) { // User.method is undefined, since User refers to User constructor await get(req, res, User.method); } async function get(req, res, f) { let start = ...; let end = ...; let params = ...; let user = new User(params); // f is undefined here let stream = await f.call(user, start, end); } 
+5
source share
1 answer

The user method is undefined because the user is referencing the constructor

You are looking for User.prototype.method :

 async function getData(req, res) { await get(req, res, User.prototype.method); } 

Remember that ES6 class material is syntactic sugar on top of a prototype language.

+4
source

All Articles