I'm trying to call a method from a require
d Node module with a specific this
object. As far as I see, there are three ways to do this, with .bind(obj)(args)
, or with .call(obj, arg1, ...)
, or with .apply(obj, aryArgs)
. I'm currently using bind
, but I have tried all three with identical levels of not-success.
This is where I'm running the call:
var library = require("./library.js");
// ...
requestHandler.bind(library)(req);
requestHandler
is a reference to the exported status
function from this file:
exports.status = () => {
console.log(this);
this.render({text: "status ok"});
};
exports.paramSwitching = () => {
this.render("rendered via param switching");
};
exports.json = () => {
this.render({json: {this: 'renders', as: 'json'}});
};
exports.view = () => {
this.render({view: true, locals: {text: 'hi'}});
};
I'd like this to work so that the status
function is called with library
as its this
object, since that's where render
is defined. However, the console.log
statement is showing this
as the evaluated contents of the file holding status
, i.e.
{ status: [Function],
paramSwitching: [Function],
json: [Function],
view: [Function] }
What's happening here, and how do I fix it? (Or, if I can't because Node is doing something weird, is there a workaround?)