Sunday, 15 July 2012

inheritance - How to "subclass" a node.js module -



inheritance - How to "subclass" a node.js module -

i've been perl coder years, have background in c++, i'm coming "classical" oo background, , learning node.js. read through the principles of object-oriented javascript, did job of explaining js concept of oo classically-minded people me. i'm left question, related node.js , inheritance. pardon me if i'm still using "classical" vocabulary explain problem.

lets suppose have module lib/foo.js:

function foo() { console.log('foo called'); } module.exports.foo = foo;

and want "subclass" in module lib/bar.js:

var foo = require('foo.js'); // magic here *.prototype, maybe? function bar() { console.log('bar called'); } module.exports.bar = bar;

such main script can this:

var bar = require('lib/bar.js'); bar.foo(); // output "foo called" bar.bar(); // output "bar called"

is possible? if so, missing?

or anti-pattern? or plain impossible? should instead?

here's how did it, override 1 method in request module. warning: many node modules poorly designed extension, including request, way much stuff in constructor. not gazillion argument options, starting io, connections, etc. example, request http connection (eventually) as part of constructor. there no explicit .call() or .godoit() method.

in example, wanted utilize querystring instead of qs format forms. module cleverly named "myrequest". in separate file named myrequest.js have:

var request = require('request/request.js'); var querystring = require('querystring'); myrequest.prototype = object.create(request.prototype); myrequest.prototype.constructor = myrequest; // jury rig constructor "just enough". don't parse gazillion options // in case, wanted patch post request function myrequest(options, callbackfn) { "use strict"; if (callbackfn) options.callback = callbackfn; options.method = options.method || 'post'; // used posts request.prototype.constructor.call(this, options); // ^^^ trigger everything, including actual http request (icky) // @ point can't alter more } // override form method utilize querystring stringify myrequest.prototype.form = function (form) { "use strict"; if (form) { this.setheader('content-type', 'application/x-www-form-urlencoded; charset=utf-8'); this.body = querystring.stringify(form).tostring('utf8'); // note this.body , this.setheader fields/methods inherited request, not added in myrequest. homecoming this; } else homecoming request.prototype.form.apply(this, arguments); };

then, in application, instead of

var request = require("request"); request(url, function(err, resp, body) { // here });

you go

var myrequest = require("lib/myrequest"); myrequest(url, function(err, resp, body) { // same here });

i'm not javascript guru there may improve ways...

node.js inheritance node-modules

No comments:

Post a Comment