godzsa godzsa - 9 months ago 50
Javascript Question

How to pass res.json as a callback function?

I have a function with a callback parameter. I use it this way, and it works just fine:

DB.last(user,(data) => res.json(data));

I tried to rewrite it to something like this, to make it more readable:

where DB.last is

static last(user, callback) {
let data = {name: user, registered: new Date()};

The function call DB.last is in an express router script of course.

I think I see the difference between the two but it seems logical to me to pass res.json to my DB module as a callback parameter (I mean I can pass a function in JS), but it won't work this way.

What am I missing? Why won't this work?


You have to use res.json.bind(res).

When you call res.json(), it is executed on the res object (i.e. this value refers to res when the function is executed). However, when you pass res.json as a callback parameter, and then call it as callback(), it is executed on the object which is this in the context where callback() is called.

Using the bind() method forces the function to be called on res. Whenever you call the bound function, its this value will always be res.