9

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

1 Answer 1

4

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.