Approaches to modular client-side Javascript without namespace pollution

后端 未结 8 1291
借酒劲吻你
借酒劲吻你 2021-02-02 02:14

I\'m writing client-side code and would like to write multiple, modular JS files that can interact while preventing global namespace pollution.

index.html



        
8条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-02 02:51

    I would strongly recommend you to go ahead with RequireJS.


    The modules support approach (without requires/dependencies):

    // moduleA.js
    
    var MyApplication = (function(app) {
    
        app.util = app.util || {};
    
        app.util.hypotenuse = function(a, b) {
            return Math.sqrt(a * a + b * b);
        };
    
        return app;
    })(MyApplication || {});
    
    // ----------
    
    // moduleB.js
    
    var MyApplication = (function(app) {
    
        app.util = app.util || {};
    
        app.util.area = function(a, b) {
            return a * b / 2;
        };
    
        return app;
    })(MyApplication || {});
    
    // ----------
    
    // index.js - here you have to include both moduleA and moduleB manually
    // or write some loader
    
    var a = 3,
        b = 4;
    console.log('Hypotenuse: ', MyApplication.util.hypotenuse(a, b));
    console.log('Area: ', MyApplication.util.area(a, b));
    

    Here you're creating only one global variable (namespace) MyApplication, all other stuff is "nested" into it.

    Fiddle - http://jsfiddle.net/f0t0n/hmbb7/


    **One more approach that I used earlier in my projects - https://gist.github.com/4133310 But anyway I threw out all that stuff when started to use RequireJS.*

提交回复
热议问题