godzsa godzsa - 2 months ago 13
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:
DB.last(user,res.json);


where DB.last is

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


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?

Answer

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.

Comments