In node.js, instead of :
dummy = require('dummy')
dummy.aMethod()
dummy.anotherMethod()
I want to use directly the methods in my context :
dummy = require('dummy')
loadMethods(dummy)
aMethod()
anotherMethod()
How can I implement the function loadMethods ?
One thing you can do is to use
with, like this:That’s not recommended though, as it makes a lot of things ambiguous and not behaving as you would expect them to.
To do exactly what you’re asking for, you can add these methods to the
globalobject. You can use something like this:This approach has its limitations too, though – for example, you can’t use aMethod() in the body of a function, the
thisobject will be wrong (of course, you could usebindto keep it correct). Also,globalis not really global, but module-scoped – so every module gets its ownglobalobject.So, weighing the options, you should probably stick with using the methods through
dummy. This way you’ll always get the expected behavior (thiswill bedummy) and you’ll have a clear indication that the methods you’re using are actually implemented in thedummymodule and use its state. Find a good IDE and typing shouldn’t be a problem.