Quote:
Originally Posted by felgall
There are some places in JavaScript where you have to define the functions the way I did. For example if you want to define the function two different ways using an if statement to select which of the two definitions to use or if you nest definitions of the same function inside one another.
For example of you are going to define an addEvent function that uses an eventListener for JavaScript and attachEvent for JScript then you have to define the two functions the way I did because the way you defined the functions is not allowed inside of if/else. See http://javascriptexample.net/events01.php for an example of this.
|
if your claim is true, why does this seem to work?
Code:
function test(x,y){
function sum(a,b){return a+b;}
if( 1>0 ){function sum(a,b){return a*b;}}
return sum(x,y);
}
test(5,10); // == 50
as compared to :
Code:
function test(x,y){
function sum(a,b){return a*b;}
if( 1>0 ){ function sum(a,b){return a+b;} }
return sum(x,y);
}
test(5,10); // == 15
seems like the function statement inside the if work just fine to me, unless you know something i don't...
i can see how with function hoisting and all one might think it wouldn't work, but it's neat how it works as expected, huh?
I for one, strongly recommend using function statements instead of function expressions, it's one less name to type, and gives all functions an internal name. This is important since arguments.callee is likely going away soon. When you pre-declare the var, and then later assign the function without an internal name, recursion is slower and more dangerous, and you have more boilerplate between the function opener and the core logic. That's harder to skim, even if it is more detailed information.
if i were to code the OP's syntax, i would DRY all vars and assumed globals, publish the workhorse for later re-use, make it async and dependency self-aware, self-waiting for all depends, and use better function declaration to reduce clutter, allow recursion, and facilitate debugging:
PHP Code:
// wrap your entire script inside a function so that nothing is global
(function wrapper() {
// define local variables
var myGlobal1=myGlobal1;
// init code:
function main() {
// normally more would be put here, but this is an example
// for learning sake.
exampleFunc();
alert("application has terminated.");
}
// support code:
function exampleFunc() {
alert(myGlobal1.value);
}
// invoke init and execution if ready:
if(myGlobal1){
main();
} else {
return setTimeout(wrapper);
}
//optional, publish main() for partial page refreshes to re-init this app:
self.main = main;
}()); // end wrapper()
to me, that code is much less terse, more stable, and has a good self-narrative instead of a formal introduction.