What is the correct way to extend a class defined in a JavaScript Universal Module (UMD file)

391 Views Asked by At

I've made a first attempt at a custom log "appender" for log4javascript. It works, but it is stuck inside the original code. I want to keep my extension in a separate file, but I don't understand the rest code well enough to know how to extract it.

I understand that log4javascript respects the UMD pattern somehow, but that's as far as I have got.

(Although shouldn't it be...

(function(root, factory){})(this, function{})...

... instead of ...

(function(factory, root){})(function{})

... ????*)

(function(factory, root) {
    if (typeof define == "function" && define.amd) {
        define(factory);
    }
    else if (typeof module != "undefined" && typeof exports == "object") {
        module.exports = factory();
    }
    else {
        root.log4javascript = factory();
    }
})(function() {

        :
  Here be dragons . . .
        :


    /*  -- -  this code works from here, but not if I    - -- */
    /*  -- -  try to move it out to a file of its own    - -- */    
    function MyAppender() {}
    MyAppender.prototype = new Appender();
    MyAppender.prototype.layout = new SimpleLayout();
    MyAppender.prototype.append = function(loggingEvent) {
      alert( this.getLayout().formatWithException(loggingEvent) );
    };
    MyAppender.prototype.toString = function() {
      return "MyAppender";
    };
    log4javascript.MyAppender = MyAppender;
    /*  -- -      -   -   -   -   -   -   -   -   -      - -- */    



        :
 . . . and sea monsters
        :


    return log4javascript;
}, this);

How can I subclass Appender in a separate file?

1

There are 1 best solutions below

0
On

Since posting a few hours ago, I've been reading more about UMD, AMD, requireJS, etc.

The main issue is name space purity, it seems.

Having figured that out, all I had to do was solve the name space problem. It turns out to be stupidly easy: it's right there in the code! Duh! :

log4javascript.MyAppender = MyAppender;

Instead of . . .

MyAppender.prototype = new Appender();
MyAppender.prototype.layout = new SimpleLayout();

... I just had to do ...

MyAppender.prototype = new log4javascript.Appender();
MyAppender.prototype.layout = new log4javascript.SimpleLayout();