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:
with (dummy) {
aMethod();
anotherMethod();
}
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 global object. You can use something like this:
for (var prop in dummy) {
if (dummy.hasOwnProperty(prop)) {
global[prop] = dummy[prop];
}
}
This approach has its limitations too, though - for example, you can't use aMethod() in the body of a function, the this object will be wrong (of course, you could use bind to keep it correct). Also, global is not really global, but module-scoped - so every module gets its own global object.
So, weighing the options, you should probably stick with using the methods through dummy. This way you'll always get the expected behavior (this will be dummy) and you'll have a clear indication that the methods you're using are actually implemented in the dummy module and use its state. Find a good IDE and typing shouldn't be a problem.
Take advantage of the malleability of this. When a function is called without being bound to a specific scope for this (which can be done through .call, .apply, or in a method-context) then this refers to the global object. This code will work in browsers as well as Node.js, but will of course overwrite any other globally-scoped function with the same name. Use with caution...in general I'd recommend against using it.
function loadMethods(obj) {
for (var prop in obj) {
if (obj.hasOwnProperty(prop) && typeof(obj[prop]) === 'function') {
this[prop] = obj[prop]
}
}
}
You can learn more about this context here