javascript - How to inherit from a "constructor returns another object" object -


the node-binary binary parser builds object following pattern:

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

how inherit own, enlightened parser this? pattern designed intentionally make inheritance awkward?

my successful attempt far @ inheriting methods of binary.parse(<something>) use _.extend as:

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

this has failed smell test, , of others. there 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 plain object (an object inherits object.prototype), , not possible redirect prototype link subsequently (unless __proto__, that's non-standard , deprecated).

so, thing can do, extend object our methods manually...

btw, clever_parser function works fine factory function. don't have bother constructors, , new operator.


also, can take opposite approach: first, create object inherits methods, , extend properties assigned in binary.parse function:

var clever_parser = function ( buffer ) {     var parser = object.create( clever_parser.methods );     _.extend( parser, binary.parse( buffer ) );     return parser; } 

if approach works, better original solution above, since here resulting object inherits methods (as opposed above, each instance contains methods own properties).


Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -