I've been reading quite a bit about the method bind()
and I am beginning to understand that it sets this
to a specific object. That almost always means that there is this
somewhere within the function definition that is pointing to a certain object. However, I've seen in instances where bind()
is used without this
in the definition of the functions. More specifically, this
is used as an argument, which confuses me. For example,
const eventLoader = new DataLoader((eventIds) => {
return events(eventIds);
});
const events = async eventIds => {
try {
const events = await Event.find({ _id: { $in: eventIds } });
return events.map(event => {
return transformEvent(event);
});
} catch (err) {
throw err;
}
};
const user = async userId => {
try {
const user = await userLoader.load(userId.toString());
return {
...user._doc,
_id: user.id,
createdEvents: eventLoader.load.bind(this, user._doc.createdEvents)
};
} catch (err) {
throw err;
}
};
In this example, eventLoader.load.bind(this, user._doc.createdEvents)
uses this
as an argument for bind()
even though the eventLoader
function nor the events
function have this
in their function definition. Isn't the first argument of bind() where you want the pre-existing this
to point towards?