Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static import in JavaScript

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?

like image 911
Joshua MN Avatar asked Feb 21 '13 08:02

Joshua MN


3 Answers

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.

like image 56
emesx Avatar answered Sep 26 '22 19:09

emesx


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.

like image 27
Alexander Pavlov Avatar answered Sep 22 '22 19:09

Alexander Pavlov


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.

like image 27
sitifensys Avatar answered Sep 23 '22 19:09

sitifensys