How to inherit from a non-prototype object

Posted by Andres Jaan Tack on Stack Overflow See other posts from Stack Overflow or by Andres Jaan Tack
Published on 2012-06-04T22:36:46Z Indexed on 2012/06/04 22:40 UTC
Read the original article Hit count: 279

Filed under:
|
|

The node-binary binary parser builds its object with the following pattern:

exports.parse = function parse (buffer) {
    var self = {...}
    self.tap = function (cb) {...};
    self.into = function (key, cb) {...};
    ...
    return self;
};

How do I inherit my own, enlightened parser from this? Is this pattern designed intentionally to make inheritance awkward?

My only successful attempt thus far at inheriting all the methods of binary.parse(<something>) is to use _.extend as:

var clever_parser = function(buffer) {
    if (this instanceof clever_parser) {
        this.parser = binary.parse(buffer);  // I guess this is super.constructor(...)
        _.extend(this.parser, this);         // Really?
        return this.parser;
    } else {
        return new clever_parser(buffer);
    }
}

This has failed my smell test, and that of others. Is there anything about this that makes in tangerous?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about node.js