If I have a module with a public member and I use it like this
Module.Sub.member()
Then what is the best (if it exists) way to static import the member into local scope, like using
in cpp or import static
in Java?
var App = (function(app) {
/* Dependencies */
var Sound = app.Modules.Sound,
Input = app.Modules.IO.Input,
...
/* Actual code using dependecies */
...
})(App || {});
This solution has several advantages:
Stated at the top of a module, it's clearly visible at first glimpse (maintainable code) ,
Usual benefits of imports: less typing, avoidance of namespace clashes etc. (maintainable code)
Long property path look-ups (a.b.c.d
) will be needed only once (performance) ,
Using a local variable is faster, that using a global variable - quicker look-ups (performance),
Minification tools can minify local variable names safely, but can't trivially minify global variables.
Something like
member = Module.Sub.member;
perhaps? However be careful, as it clutters the global object properties and may even end up overwriting some of those, since you have no notion of a "compilation unit", to which static imports are scoped in Java. Instead, you have a single, dynamic execution state of your VM, so the suggestion above is not a declarative but an imperative way to achieve what your are after.
To my knowledge, there is no way to declaratively achieve the same goal as import static
does.
This is an approach I find beautiful enough to point at :
(function(member) {
//Your code here will see member in this scope.
}) (Module.Sub.member);
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With