javascript create INcode workspace (framework)

后端 未结 2 1976
無奈伤痛
無奈伤痛 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条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-27 01:55

    Use an anonymous function wrapper. Any variables which are defined using var will not be available for the code outside the wrapper. Whenever you want to define a method or property, add them to the tobepublic object (which is returned at the end).

    var your_namespace = (function(){
        //Your own "workspace"
        var tobepublic = {};
        //Define any attributes and methods which should be public on tobepublic
        tobepulic.helloWorld = function(){
            alert("Hi!");
        }
    
        return tobepublic;
    })();
    

    Publicly, the above code looks like the code below. The methods above, however can also have access to private methods/variables, which cannot be seen "from the outside":

    var your_namespace = {
        helloWorld: function(){
            alert("Hi!");
        }
    }
    

提交回复
热议问题