Possible Duplicate:
javascript create INcode workspace (framework)
In the last few days i have been interesting in how Javascript framework have they own workspace , what i mean is how they can call a variable at any name they want and work with it without involving local variables.
I’m writing now an API and i’m facing the problem of the local variables / function local names , if they already exist.
So , what i have done is looking into how framework works and i saw they use namespace functions like this :
(function(){ .... })()
so i tried to do something alike
<html>
<head>
<script type="text/javascript">
(function() {
function f(toAlert) { alert(toAlert); }
})();
</script>
</head>
<body>
<script>
toAlert("hi");
</script>
</body>
</html>
but it’s not working..
so i have few questions :
-
how to have a workspace in javascript to set any variable name i want (if function too it would be great).
-
i saw that the frameworks uses “window” command , is it have something to do with the namespace function to “public” the function or w/e?
-
i’ll be glad if you can give me information / tutorials about all this thing , how to make it done from beginning to ending
of course it’s not working, because your
f(toAlert)function is only visible within the immediately executing function closure scope. And you’re also trying to call some function that doesn’t exists in the first place. Your closure function is calledf(and hastoAlertparameter), and then you’re trying to call function calledtoAlertthat wasn’t defined anywhere. Not in global nor in closure 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:
Putting it in parentheses and adding some at the end, executes it right away:
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.
omitting
varor referencingwindowobject makes a function or variable global.