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?
Create a function closure local scope.
This code may clear things up a bit for you. Read comments.
<script type="text/javascript">
// global scope
function globalFunc(text) {
alert(text);
}
var privateFunc = null;
// function closure scope
(function(){
// closure function
function closureFunc(text) {
// can call global
globalFunc(text);
}
// let's make closure function accessible from global scope
// since privateFunc variable is in global scope
privateFunc = closureFunc;
})();
// call closure function
privateFunc("calling closure function");
// ERROR: this will not work due to function being in closure scope
closureFunc("calling closure function");
</script>
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...
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.
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!");
}
}