Reputation: 6025
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.
Upvotes: 13
Views: 5697
Reputation: 4057
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.
Upvotes: 7
Reputation: 65539
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();
// ...
};
})();
Upvotes: 3