Javascript Namespacing

前端 未结 3 1357
遥遥无期
遥遥无期 2020-12-14 23:40

I wish to make my javascript more more modular by splitting it up into different files and giving each file a \'sub\' namespace like so.

subA.js

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-15 00:32

    1. The function(){ return{}} is a closure to add "privacy" to the variables and functions you don't want to be accessible anywhere else but within the scope of that function. The parentheses around the function (function(){}) create a function expression. They are used, because the parser will complain when you try to execute a function immediately function(){}() without passing any argument to ().

    2. If you want subA or any other extending object to have its own subfunctions, then yes, you have to declare it like that, but not neccesarly a clousure though.

    You can do

    ex.subA = function(x, y){
        return x+y;
    }
    

    which can be called var sum = ex.subA(2, 3);

    Or you can do

    ex.subA = (function(){
    
        return {
            add: function(x, y){
                return x+y;
            },
            multiply: function(x, y){
                return x*y;
            }
        }
    })();
    

    Then call it var sum = ex.subA.add(2, 3); var multiplication = ex.subA.multiply(2,3);

    There are many ways to do this.

    3. Yes, it is true. You can make the private functions public. The closure won't allow any other way to do it.

    4. If you would like to alias, yes you can assign it to a variable. However, there is no need to. It will work fine the way you are describing it.

    Read Essential JavaScript Namespacing Patterns to understand some fundamentals and patterns in javascript namespacing.


    Is the first if statement in subA.js any different from var ex = ex || {}; Which is better?

    First of, the if statement should be if(typeof ex == 'undefined'), the typeof returns a string. There isn't any need to check if ex is false.

    Yes, it is different. The if statement will not do any variable assignment if the variable ex is already defined. Therefore, the if statement is better.

    What js code style standards do you use?

    Depends on the scope of the project, but mostly deep object extending with a helper function.

提交回复
热议问题