Say I got two functions that looks like this:
function main(Index)
{
doStuff();
}
function doStuff()
{
if(Index == 1)
{
document.write("Hello world!")
}
}
And some HTML:
<input type="button" value="Click me" onclick="main(1)" />
I realize this is a very stupid way to use function-specific variables and such, but it's just out of curiosity. So is it possible to pass the variable Index from the main function to the doStuff function?
-
1What you're looking for is called dynamic scoping. Some languages have this feature, but not javascript.georg– georg2012年11月10日 15:42:07 +00:00Commented Nov 10, 2012 at 15:42
-
You can use a simple closure to achieve this functionality. See my answer below.elucid8– elucid82012年11月10日 17:09:00 +00:00Commented Nov 10, 2012 at 17:09
3 Answers 3
So is it possible to pass the variable Index from the main function to the doStuff function?
No, not without explicitly passing it as a parameter to doStuff. Either doStuff needs to accept a parameter or it could utilize the arguments collection:
function main(index)
{
doStuff(index);
}
function doStuff()
{
var index = arguments[0];
if(index == 1)
{
document.write("Hello world!")
}
}
2 Comments
This is the only way:
function doStuff(Index)
{
if(Index == 1)
{
document.write("Hello world!")
}
}
or making it a global variable
Comments
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).