javascriptnode.jsinheritancecompoundjs

Node JS: Accessing inherited function in subclass's function


Let's say I have two classes, Base and Child. Base is the base class that Child will be inheriting from. Here's the code to visualize this:

Base.js

function Base(init) {

}

function log() {
  console.log('here');
}
Base.prototype.log = log;

module.exports = Base;

Child.js

var Base = require('../Base.js');

var Child = module.exports = function Child(init) {
  Base.call(this, init);
};

require('util').inherits(Child, Base);

function test() {
  this.log();  // doesn't work
  Base.prototype.log();  // Works but is quite ugly
  Child.super_.prototype.log();  // Works but is even uglier
}

Child.prototype.test = test;

What I would absolutely love to do is something like this.log() or even log() would be nice. I realize I can set a variable to that in my inherited class, but then I would have to do that for every class that inherits Base, which is definitely not ideal. So my question is, can I do something like this.log() without having to set a variable in the inherited class? Am I misunderstanding something?


Solution

  • Just as an FYI, I ended up putting this in the global variable that Node creates for you. I realize that's bad practice, but it's a logging mechanism that needs to be used by any class, controller, etc., so I don't think it's that terrible of a solution.

    However, in Compound, you can create no_eval controllers, which means they look like typical prototypical functions... so you can essentially create a mixin, or I can require my mixin and use it like a class... like this:

    var ControllerMixin = require(process.cwd() + 'app/mixins/ControllerMixin.js');
    var Log;
    
    var LoggerController = module.exports = function LoggerController(init) {
      ControllerMixin.call(this, init);  // mixin approach
      Log = require(process.cwd() + 'app/utils/LoggerMixin.js')(init);  // class approach
    };
    
    LoggerController.prototype.index = function index(controller) {
      controller.logMessage('blah');  // using mixin
      Log.logError('hi');  // using class
      global.logWarning('yep');  // global approach
      return controller.send({success: true});
    };
    

    So there are options... just have to find what you think is the best approach.