RobinL RobinL - 4 months ago 8
Javascript Question

Is it possible to 'import' part of a namespace (a module) into the current scope?

I have one module called functionalUtilities which contains a number of utility functions. An abbreviated version looks something like this:

MYAPP.functionalUtilities = (function() {
function map(func, array) {
var len = array.length;
var result = new Array(len);
for (var i = 0; i < len; i++)
result[i] = func(array[i]);
return result;
}
return {
map:map,
};
})();


I then have a second module which contains core code:

MYAPP.main = (function() {

//Dependencies
var f = MYAPP.functiionalUtilities;

//Do stuff using dependencies
f.map(...)

})()


It seems messy and annoying having to remember to type
f.map
each time I want to use
map
. Of course, in the dependencies, I could go though each of my functionalUtilities typing:

var map = f.map,
forEach = f.forEach,


etc.

but I wondered whether there is a better way of doing this? A lot of articles on namespacing that I've read mention aliasing, but don't suggest a way to sort of 'import all of the contents of an object into scope'.

Thanks very much for any help,

Robin

[edit] Just to clarify, I would like to use my functional utilities (
map
etc) within
MYAPP.main
without having to preface them every time with
f.


This is possible by going through each function in
MYAPP.functionalUtilities
and assigning to a locally scoped variable within
MYAPP.main
. But the amount of code this requires doesn't justify the benefit, and it's not a general solution.

Answer

As I said in the comment. There is no real way of automatically defining local variables out of object properties. The only thing that comes to my mind is using eval:

for (var i in MYAPP.functiionalUtilities) {
    eval("var " + i + " = MYAPP.functiionalUtilities[i];");
}

But I wouldn't use this method, since you could have object properties with strings as keys like this:

var obj = {
    "my prop": 1
};

"my prop" might be a valid key for an object property but it's not a valid identifier. So I suggest to just write f.prop or define your local variables manually with var prop = f.prop;

EDIT

As Felix Kling mentioned in the comment section, there is in fact another way of achieving this, using the with statement, which I don't really know much about except for that it is deprectated.