Why are you shifting that call to the the DoStuff function?
Isn't the point of Main to react to an event and "do stuff"?
If that's the case, you should just keep that functionality in Main, like this:
function Main(index){
switch (index){
case 1:
DoStuff();
break;
case 2:
DoStuff2();
break;
default:
DoStuff(); //Because, why not?
{
}
function DoStuff(){
document.write("Hello, world!");
}
function DoStuff2() {//something else happens here}
You aren't using Main as an object, so there is no need for persistence (as far as I know). Just cut out the unnecessary call and your life will be simpler. However, you can create a simple closure if you're hell bent on achieving this kind of functionality. It would look like this:
<input type="button" onclick="Main(1);" value="Do Something" />
<script type="text/javascript">
function Main(index) {
//This function only exists within the scope of Main
function DoStuff() {
//But now it has the added benefit of knowing about index
switch (index) {
case 1:
alert("Hello, world!");
break;
case 2:
alert("Not, really. I'm mad.");
break;
default:
alert("Hello, world!");
}
}
//Now Main is going to call it's internal function and...
DoStuff();
}
</script>
Since you declared DoStuff within the body of Main that means that DoStuff exists within the lexical scope of Main and will have access to all of its members. Closures are really powerful, but it's easy to abuse them. If you really need this kind of functionality, I'd suggest going this route, but otherwise, KISS (Keep It Simple Sir).