rodrigo-silveira rodrigo-silveira - 2 months ago 8x
Node.js Question

Extending Node.js Modules with OOP

Am I missing something, or is it just not possible to extend arbitrary Node modules like you would, say, a Java class?

Concrete example:

I need
to expose the
object to the
method. What I tried to do was to extend that function (
), modify the
function, then delegate to the original parent class' function for the actual business logic:

// 1: Extend RememberMeStrategy
function IWillRememberYou (options, verify, issue) {, options, verify, issue);

util.inherits(RememberMeStrategy, IWillRememberYou);

// 2: Override some method
IWillRememberYou.prototype.authenticate = (req, options) => {
// Save original function
const issue = this._issue;

// Wrap the supplied callback so it can now be sent extra args
this._issue = (user, issued) => {
// Send in additional parameter
issue(req, user, issued);

What this gives me is an empty
context inside
as well as inside
. Why is this happening??

What the parent class looks like (the third-party Node module)

function Strategy(options, verify, issue) {
// ...;

// ...
this._issue = issue;

util.inherits(Strategy, passport.Strategy);

Strategy.prototype.authenticate = function(req, options) {
// ...

// My end goal is to send (req, user, issued) to that callback
this._issue(user, issued);


Don't use arrow functions when doing OO. That's because arrow functions are deliberately designed to break how this works. Instead do:

IWillRememberYou.prototype.authenticate = function (req, options) {
  /* .. */

Remember, with arrow functions you basically bind this to the context where the function is defined. If you defined it outside of any function then this will be the global object or undefined if in strict mode.

What this boils down to is that arrow functions breaks inheritance.