I'm not sure if it's possible, but I'll still ask whether it is.
I want to make a module that could be used in either one of the two ways :
Like this:
MyModule = require('mymodule'); MyModule.do('stuff');modules outputs stuff
Or like this: (called with an additional argument)
MyModule = require('mymodule')('some'); MyModule.do('stuff');modules outputs "some" stuff
I tried to make it liks so
function MyModuleThatDoesntTakeArguments(argument){
function MyModuleThatTakesArgument(){
this.argument = argument;
}
// this will be called when arguments are passed
MyModuleThatTakesArgument.prototype.do = function(){
console.log('outputs', argument, 'stuff');
}
// this* will be called when no arguments are passed
this.do = function(){
console.log('outputs stuff');
}
return MyModuleThatTakesArgument;
}
// or this* will be called when no arguments ″ ″
MyModuleThatDoesntTakeArguments.prototype.do = MyModuleThatDoesntTakeArguments.do;
module.exports = MyModuleThatDoesntTakeArguments;
It works when called with an argument (#1) but gives an error like "Function Object doesn't have a method do".
I'm realizing the basic problem is that it can either be called as a constructor function (when called with argument (#1)) which makes it return the inner function., But when called without the argument (#2) it just returns the constructor itself, which unfortunately can't have its method (this.do or .prototype.do) called and thus gives that error.
So I guess the whey I'm writing it it's not possible.
Is it still possible some other way to achieve what I want?
dofunction to the function itself instead of the prototype (and read a bit about how prototypes in JS work). - jgillich