Approaches to modular client-side Javascript without namespace pollution

后端 未结 8 1282
借酒劲吻你
借酒劲吻你 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:38

    So called "global namespace pollution" is greatly over rated as an issue. I don't know about node.js, but in a typical DOM, there are hundreds of global variables by default. Name duplication is rarely an issue where names are chosen judiciously. Adding a few using script will not make the slightest difference. Using a pattern like:

    var mySpecialIdentifier = mySpecialIdentifier || {};
    

    means adding a single variable that can be the root of all your code. You can then add modules to your heart's content, e.g.

    mySpecialIdentifier.dom = {
        /* add dom methods */
    }
    (function(global, undefined) {
        if (!global.mySpecialIdentifier) global.mySpecialIdentifier = {};
        /* add methods that require feature testing */
    }(this));
    

    And so on.

    You can also use an "extend" function that does the testing and adding of base objects so you don't replicate that code and can add methods to base library objects easily from different files. Your library documentation should tell you if you are replicating names or functionality before it becomes an issue (and testing should tell you too).

    Your entire library can use a single global variable and can be easily extended or trimmed as you see fit. Finally, you aren't dependent on any third party code to solve a fairly trivial issue.

提交回复
热议问题