javascript create INcode workspace (framework)

后端 未结 2 1975
無奈伤痛
無奈伤痛 2021-01-27 01:11

in a case i have a little \"framework\" for the public , how can i make my own \"workspace\"? so i can use what ever variable name i want?

how can i make it done?

2条回答
  •  梦毁少年i
    2021-01-27 01:40

    Create a function closure local scope.

    Scope?

    This code may clear things up a bit for you. Read comments.

    
    

    Creating local scope

    What does that strange function parentheses actually do?

    This is some function:

    function name(someParameter) { ... }
    

    Putting it in parentheses and adding some at the end, executes it right away:

    (function name(someParameter) { ... })("Parameter text value");
    

    Mind the function parameter...

    Why do libraries use local scope?

    Libraries usually use local scope to not pollute and more importantly clash with other possible libraries. Think of two libraries that would both define a function called getName. The last one that would define it would simply override the first one's implementation thus making the first library to malfunction.

    When each library creates its own closure scope they can create whatever functions, variables within and use them without the fear of being overridden. Libraries usually just expose some small part into global scope, so other scripts can actually use the library.

    (function() {
    
        var closureVar = "I'm local";
    
        globalVar = "I'm global";
        // or
        window.globalVar2 = "I'm global equivalent";
    
    })();
    

    omitting var or referencing window object makes a function or variable global.

提交回复
热议问题