oop - Parametrized module loading in Node.js -
i working on first node.js project , have come oop problem not sure how solve in node.js.
i have module a:
module.exports = a; function a() { } a.prototype.method = function() { return "a";}; //other methods...
and couple other modules (lets b , c) implement same "interface" a.
now, have module x:
module.exports = x; function x(impl) { //choose a, b, or c based on value of impl }
so question is, how implement x in order able do:
var x = require("x"); var impl = new x("a"); impl.method(); //returns "a"
i believe prototype
, __proto__
involved?
edit: trying achieve load implementation a, b or c, based on string value (env variable) through standartized interface new x()
, access methods of a(b,c...) through instance of x.
i think you're after:
a.js (b.js , c.js similar, of course):
function a() {} a.prototype.method = function() { return 'a'; }; module.exports = a;
x.js:
var modules = { a: require('./a'), b: require('./b'), c: require('./c') } function x(impl) { if(impl in modules) return new modules[impl]; else throw new error('unknown impl: ' + impl); } module.exports = x;
usage:
var foo = new x('a'); foo.method(); // => 'a' var bar = new x('b'); bar.method() // => 'b'
an alternative keeping modules
object in x
require
inside x(impl)
, let require
throw error:
function x(impl) { return new require('./' + impl); }
Comments
Post a Comment