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?
How about:
var clever_parser = function ( buffer ) {
var parser = binary.parse( buffer );
_.extend( parser, clever_parser.methods );
return parser;
}
clever_parser.methods = {
foo: function () { ... },
bar: function () { ... }
};
The binary.parse
function returns a plain object (an object that inherits from Object.prototype
), and it is not possible to redirect its prototype link subsequently (unless with __proto__
, but that's non-standard and deprecated).
So, the only thing we can do, is extend that object with our methods manually...
Btw, the clever_parser
function works fine as a factory function. You don't have to bother with constructors, and the new
operator.
Also, you can take the opposite approach: first, create your object that inherits your methods, and then extend it with the properties that are assigned in the binary.parse
function:
var clever_parser = function ( buffer ) {
var parser = Object.create( clever_parser.methods );
_.extend( parser, binary.parse( buffer ) );
return parser;
}
If this approach works, it is certainly better than my original solution above, since here the resulting object inherits your methods (as opposed to above, where each instance contains the methods as own properties).