Javascript: nesting private functions - good or bad?

I often use this structure:

var example = (function () { function privateFn2 () { ... } function privateFn1 () { ... } return { publicMethod1: function () {... }, publicMethod2: function () {... } }; }()); 

I want to know the following: If privateFn1 is the only function / method that calls privateFn2, is it considered best practice to set it up as follows?

EDITED for clarity

 var example = (function () { function privateFn1() { function privateFn2() { } ... privateFn2(); } return { publicMethod1: function () {... }, publicMethod2: function () {... } }; }()); 

This, of course, is a simplified example. The problem is that I have many private functions, and I wonder if nesting is good or bad. I admit that this is most likely a matter of preference, but any advice would be greatly appreciated.

Thanks.

+8
javascript function nested
source share
2 answers

It depends on situation. If you have several private functions that relate only to another private function, perhaps this is a situation where an object or class packs more functionality than it should be.

Here are some questions to ask:

  • Do these private functions have side effects? That is, do they manipulate any closed properties? If not, are these some generalized logics that can be implemented statically and included separately? Or do these private functions control a subset of properties that can be transferred to another class or object?
  • Whether private functions are simple helper functions for specific tasks to be used inside a larger algorithm or control function; such as a filter function to sort an array or some other iteration callback? If so, then it may actually be to embed these functions inside and not go out of scope of the main object. Will any other code need these features?
  • How many times will the main private function be called? If it is called very often (inside the loop or by timer interval), then inserting private functions inside can bear measurable overhead - which would otherwise be insignificant if the private function were called only occasionally.

There are always trade-offs to consider; thinking about these issues will help you decide what is best for your particular situation.

+5
source share

I would avoid your second example. Each time privateFn1 is privateFn1 , it overrides privateFn2 . Why not just do it once? You might even need to use it somewhere else later.

However, if you really want to hide privateFn2 , the best solution would be the following:

 var privateFn1 = (function () { function privateFn2() { // ... } return function () { privateFn2(); // ... }; })(); 
+3
source share

All Articles