I'm frequently using this structure:
var example = (function () {
function privateFn2 () {
...
}
function privateFn1 () {
...
}
return {
publicMethod1: function () {...
},
publicMethod2: function () {...
}
};
}());
What I want to know is this: If privateFn1 is the only function/method that calls privateFn2, is it regarded as better practice to set it up as follows?
EDITED for clarity
var example = (function () {
function privateFn1() {
function privateFn2() {
}
...
privateFn2();
}
return {
publicMethod1: function () {...
},
publicMethod2: function () {...
}
};
}());
This is a wildly simplified example, of course. The issue is that I have lots of private functions, and I'm wondering whether nesting is well- or poorly-regarded. I recognise it is quite possibly a matter of preference, but any advice will be gratefully received.
Thanks.
no, there's nothing wrong with that at all, and in js, it's usually a good thing. the inside functions may not be a pure function, if they rely on closure variables. If you don't need a closure or don't need to worry about polluting your namespace, write it as a sibling.
Nested functions It can access the outer variables and so can return the full name. Nested functions are quite common in JavaScript. What's much more interesting, a nested function can be returned: either as a property of a new object or as a result by itself. It can then be used somewhere else.
You should put it at global scope, for several reasons. Nesting a helper function into the caller increases the length of the caller. Function length is almost always a negative indicator; short functions are easier to understand, to memorize, to debug and to maintain.
A nested function can access other local functions, variables, constants, types, classes, etc. that are in the same scope, or in any enclosing scope, without explicit parameter passing, which greatly simplifies passing data into and out of the nested function. This is typically allowed for both reading and writing.
It depends on the situation. If you have several private functions that are only relavent to yet another private function, then perhaps this is a situation where the object or class is packaging more functionality then it should be.
Here are some questions to ask:
There are always trade-offs to consider, thinking about these questions will help you decide what is best for your particular situation.
I would avoid your second example. Every time privateFn1
gets called, it redefines privateFn2
. Why not just do it once? You might even need to use it somewhere else later on.
However, if you really want to hide privateFn2
, a better solution is this:
var privateFn1 = (function () {
function privateFn2() {
// ...
}
return function () {
privateFn2();
// ...
};
})();
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