Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing ES6 class method as a function argument to be called inside the function

How do I fix the code below in order to be able to invoke class method using call.

Class definition:

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

Trying to pass class method as a function argument:

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); 
}
like image 340
krl Avatar asked Aug 29 '15 12:08

krl


1 Answers

User method is undefined, since User refers to constructor

You're looking for User.prototype.method:

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

Remember that the ES6 class stuff is syntactic sugar on top of the prototypical nature of the language.

like image 72
T.J. Crowder Avatar answered Oct 11 '22 13:10

T.J. Crowder