I have just learned about the difference between Function Declarations and Function Expressions. This got me wondering about whether or not I'm doing things right in my AngularJS code. I'm following the pattern used by John Papa, but now it seems at odds with the typical JS approach to the Module Pattern. John Papa makes heavy use of nested Function Declarations in his controllers and services. Is this bad?
Is there any reason to favor this:
var foo = (function() {
var bar = function() { /* do stuff */ };
return {
bar : bar
};
}());
foo.bar();
over this:
var foo = (function() {
return {
bar : bar
};
function bar() { /* do stuff */ };
}());
foo.bar();
I'm primarily a C# developer and still getting used to all of the nuances of JavaScript. I prefer the latter approach because all of the functions within the IIFE are private, and the revealing module pattern at the top is really the public part. In a C# class I always have my public properties and methods before the private supporting functions. However, I realize it's likely not as cut and dry in the JS world.
What are the hidden dangers (if any) of using the latter approach?
There is no functional difference between the two approaches, it's just stylistic.
The JavaScript interpreter will invisibly "hoist" the function declarations from the latter style to the top of the nested function anyway - if it didn't, the return
block would be referencing an undefined function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With